// 在文件开头添加安全获取函数
function getConfigAdmin(key, defaultValue = 0) {
    return (typeof Config !== 'undefined' && Config.admin && Config.admin[key]) ? Config.admin[key] : defaultValue;
}

// 优化的弹窗高度自适应函数
function adjustIframeHeight(delay = 100, context = 'unknown') {
    setTimeout(function () {
        try {
            // 记录调整前的页面高度
            var beforeHeight = document.body.scrollHeight;
            var success = false;
            var method = '';

            // 检查是否在iframe环境中
            if (typeof parent === 'undefined' || parent === window) {
                return;
            }

            // 方法1: 禁用 parent.Layer.full，保持弹窗原有大小
            // 注释掉全屏显示，保持 area: ['90%', '90%'], offset: ['50px', '50px'] 的设置
            /*
            if (parent.Layer && typeof parent.Layer.full === 'function') {
                try {
                    var index = parent.Layer.getFrameIndex ? parent.Layer.getFrameIndex(window.name) : null;
                    if (index) {
                        parent.Layer.full(index);
                        success = true;
                        method = 'parent.Layer.full(' + index + ')';
                    }
                } catch (e) {
                    // Layer.full方法执行失败，忽略
                }
            }
            */
            success = true;
            method = '保持原有弹窗大小（已禁用全屏）';

            // 方法2: 使用 parent.layer.iframeAuto (layui备选方案)
            if (!success && parent.layer && typeof parent.layer.iframeAuto === 'function') {
                try {
                    var index = parent.Layer && parent.Layer.getFrameIndex ?
                        parent.Layer.getFrameIndex(window.name) :
                        parent.layer.getFrameIndex ? parent.layer.getFrameIndex(window.name) : null;
                    parent.layer.iframeAuto(index);
                    success = true;
                    method = 'parent.layer.iframeAuto(' + index + ')';
                } catch (e) {
                    // layer.iframeAuto方法执行失败，忽略
                }
            }

            // 方法3: 直接设置iframe高度 (最后的备选方案)
            if (!success) {
                try {
                    var iframe = parent.document.querySelector('iframe[name="' + window.name + '"]');
                    if (iframe) {
                        var newHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) + 50;
                        iframe.style.height = newHeight + 'px';
                        success = true;
                        method = '直接设置iframe高度: ' + newHeight + 'px';
                    }
                } catch (e) {
                    // 直接设置iframe高度失败，忽略
                }
            }

            // 记录调整结果
            var afterHeight = document.body.scrollHeight;

        } catch (e) {
            // 高度调整执行出错，忽略
        }
    }, delay);
}

if ($('#row').length > 0) {
    var rowValue = $('#row').val();
    if (rowValue && rowValue.trim() !== '') {
        row = JSON.parse(rowValue);
    } else {
        row = null;
    }
} else {
    row = null;
}

window.addEventListener('keydown', function (event) {
    if (event.keyCode === 13) {
        event.preventDefault();
    }
});

var marker;

function getValue(str) {
    const selectors = [`#${str}`, `#c-${str}`, `#c-${str}2`, `#c-${str}3`, `#c-${str}4`, `#c-${str}_tree`, `#h-${str}`];
    for (const selector of selectors) {
        if ($(selector).length > 0) {
            return $(selector).val();
        }
    }

    // 安全检查Config.admin是否存在
    return (typeof Config !== 'undefined' && Config.admin && Config.admin[str]) ? Config.admin[str] : null;

}


$(document).on("change change2", "#c-rel_type", function () {
    if ($('#c-rel_id').length > 0) {
        if ($("#c-rel_type").val() == 1) {
            if ($("#c-address_lv").length > 0) {
                $("#div-address_lv").parent("div.form-group").show();
            } else if ($("#div-class_type_css").length > 0) {
                $("#div-class_type_css,#div-class_type2_css").hide();
            } else if ($("#div-subject_lv_css").length > 0) {
                $("#div-subject_lv_css,#div-subject_lv2_css").show();
            } else if ($("#c-ocation_id2").length > 0) {
                $("#c-ocation_id2").trigger("change2");
            }

            $.ajax({
                url: "/school/school/lists",
                data: { cityId: $("#city").val(), districtId: $("#county").val() },
                type: "GET",
                success: function (data) {
                    var $school = $('#c-rel_id');
                    $school.empty();
                    $school.append('<option value="">请选择学校</option>');
                    var list = JSON.parse(data);
                    $.each(list["list"], function (index, school) {
                        $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                    });
                },
                error: function (xhr, status, error) {
                }
            });
        } else if ($("#c-rel_type").val() == 2) {
            if ($("#c-address_lv").length > 0) {
                $("#div-address_lv").parent("div.form-group").hide();
            }
            if ($("#div-class_type_css").length > 0) {
                $("#div-class_type_css,#div-class_type2_css").show();
            }
            if ($("#div-subject_lv_css").length > 0) {
                $("#div-subject_lv_css,#div-subject_lv2_css").hide();
            }
            if ($("#c-ocation_id2").length > 0) {
                $("#c-ocation_id2").trigger("change2");
            }

            $.ajax({
                url: "/community/community/lists",
                data: { cityId: $("#city").val(), districtId: $("#county").val() },
                type: "GET",
                success: function (data) {
                    var $school = $('#c-rel_id');
                    $school.empty();
                    $school.append('<option value="">请选择社区</option>');
                    var list = JSON.parse(data);
                    $.each(list["list"], function (index, school) {
                        $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                    });
                },
                error: function (xhr, status, error) {
                }
            });
        }
    }
});

$("#c-rel_type").trigger("change2", function () {
    $("#c-rel_id").trigger("change2", function () {
        if ($("#c-address_lv").length > 0) {
            //$("#c-pid").val(row.pid);
        }
    });
});


$(document).on("change2 change", "#c-rel_id", function () {
    if ($('#c-pid').length > 0) {
        var $school = $('#c-pid');
        $school.empty();
        $school.append('<option value="">请选择父级</option>');
        $.ajax({
            url: "/addresslv/addresslv/lists",
            data: { relType: $("#c-rel_type").val(), relId: $("#c-rel_id").val(), cityId: $("#c-city_id").val() },
            type: "GET",
            success: function (data) {
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
            },
            error: function (xhr, status, error) {
            }
        });
    }
    if ($('#c-address_lv').length > 0) {
        var $school = $('#c-address_lv');
        $school.empty();
        $school.append('<option value="">请选择父级</option>');
        $.ajax({
            url: "/addresslv/addresslv/lists",
            data: { relType: $("#c-rel_type").val(), relId: $("#c-rel_id").val(), cityId: $("#c-city_id").val() },
            type: "GET",
            success: function (data) {
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
            },
            error: function (xhr, status, error) {
            }
        });
    }

    if ($('#c-school_id').length > 0) {
        if ($("#c-community_id").length > 0 && $('#c-rel_type').val() == 1) {
            $("#c-community_id").parents("div.form-group").hide();
        }
        if ($("#c-school_id").length > 0 && $('#c-rel_type').val() == 1) {
            $("#c-school_id").parents("div.form-group").show();
        }
        if ($('#c-rel_type').length > 0 && $('#c-rel_type').val() == 1) {
            $('#c-school_id').val($('#c-rel_id').val());
        }
    }
    if ($('#c-community_id').length > 0) {
        if ($("#c-community_id").length > 0 && $('#c-rel_type').val() == 2) {
            $("#c-community_id").parents("div.form-group").show();
        }
        if ($("#c-school_id").length > 0 && $('#c-rel_type').val() == 2) {
            $("#c-school_id").parents("div.form-group").hide();
        }
        if ($('#c-rel_type').length > 0 && $('#c-rel_type').val() == 2) {
            $('#c-community_id').val($('#c-rel_id').val());
        }
    }

});


if ($('select[name="row[province_id]"]').length > 0) {
    var $province = $('select[name="row[province_id]"]');
    $.getJSON('/cityarea/cityarea/getAreas', { level: 1 }, function (provinces) {
        $province.append('<option value="">请选择省份</option>');
        $.each(provinces, function (index, province) {
            $province.append('<option value="' + province.id + '">' + province.name + '</option>');
        });
        if (row && $("#province_id").length > 0) {
            $("#province_id").val(row.province_id);
        } else {
            $("#province_id").val(0);
        }
        // 触发加载市级数据
        var $city = $('#city');
        $province.change(function () {
            var provinceId = $(this).val();
            $.getJSON('/cityarea/cityarea/getAreas?XDEBUG_SESSION_START=54325', {
                level: 2, parent_id: provinceId
            }, function (cities) {
                $city.empty();
                $city.append('<option value="">请选择城市</option>');
                $city.append('<option value="0">区级</option>');
                $.each(cities, function (index, city) {
                    $city.append('<option value="' + city.id + '">' + city.name + '</option>');
                });
                if (row && $("#city_id").length > 0) {
                    $("#city_id").val(row.city_id);
                } else {
                    $("#city_id").val(2);
                }

                // 延迟调用updateMap，确保地图已初始化
                setTimeout(function () {
                    if ($('#c-latitude').length > 0 && window.map) {
                        updateMap(1);
                    }
                }, 500);
                // 触发加载县级数据
                $city.change(function () {
                    var cityId = $(this).val();
                    if (cityId == 0) {
                        $("#county").hide();
                        $county.empty();
                        return;
                    } else {
                        $("#county").show();
                    }
                    $.getJSON('/cityarea/cityarea/getAreas?XDEBUG_SESSION_START=54325', {
                        level: 3, parent_id: cityId
                    }, function (counties) {
                        var $county = $('#county');
                        $county.empty();
                        $county.append('<option value="-1">请选择城区（县）</option>');
                        $county.append('<option value="0">市级</option>');
                        $.each(counties, function (index, county) {
                            $county.append('<option value="' + county.id + '">' + county.name + '</option>');
                        });

                        if (row && $("#county").length > 0) {
                            $("#county").val(row.district_id);
                        } else {
                            $county.val(0);
                        }
                        if ($('#c-latitude').length > 0) {
                            updateMap(1);
                        }
                        $county.change(function () {
                            if ($('#c-latitude').length > 0) {
                                updateMap(2);
                            }
                        });
                        $("#c-rel_type").trigger("change");
                    });
                    $("#c-rel_type").trigger("change");
                });
                $city.val(2);
                $city.trigger("change");
            });
        });
        $province.val(1);
        $province.trigger("change");
    });
    $province.trigger("change");
}

// 页面加载时初始化下拉框
$(document).ready(function () {
    if ($("#c-community_id").length > 0) {
        $("#c-community_id").trigger("change2");
    }
    if ($("#c-ocation_id").length > 0) {
        $("#c-ocation_id").trigger("change2");
    }

    // 添加用户名重复检查的自定义验证规则
    if (typeof Validator !== 'undefined') {
        Validator.addRule('checkUsername', function (value, element, params) {
            var result = false;
            // 获取当前记录ID（编辑时）
            var adminId = $(element).data('admin-id') || $('#admin-id').val() || 0;
            $.ajax({
                url: 'auth/admin/checkUsername',
                type: 'POST',
                data: { username: value, id: adminId },
                async: false,
                success: function (data) {
                    if (data.valid) {
                        result = true;
                    } else {
                        $(element).data('validator-msg', data.msg);
                    }
                },
                error: function () {
                    $(element).data('validator-msg', '检查用户名时发生错误');
                }
            });
            return result;
        }, '用户名已存在');

        // 添加手机号重复检查的自定义验证规则
        Validator.addRule('checkMobile', function (value, element, params) {
            var result = false;
            // 获取当前记录ID（编辑时）
            var adminId = $(element).data('admin-id') || $('#admin-id').val() || 0;
            $.ajax({
                url: 'auth/admin/checkMobile',
                type: 'POST',
                data: { mobile: value, id: adminId },
                async: false,
                success: function (data) {
                    if (data.valid) {
                        result = true;
                    } else {
                        $(element).data('validator-msg', data.msg);
                    }
                },
                error: function () {
                    $(element).data('validator-msg', '检查手机号时发生错误');
                }
            });
            return result;
        }, '手机号已存在');
    }


    // 防抖函数
    function debounce(func, wait) {
        var timeout;
        return function executedFunction() {
            var context = this;
            var args = arguments;
            var later = function () {
                timeout = null;
                func.apply(context, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Nice-Validator的remote规则已经处理用户名验证

    // Nice-Validator的remote规则已经处理手机号验证

    // Nice-Validator的remote规则自动处理验证，不需要手动事件监听


});

$(document).on("change change2", "#c-group", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        url = "/auth/Group/lists2?XDEBUG_SESSION_START=54354";
        $.ajax({
            url: url, //data: {cityId: Config.admin['city_id'], school_id: Config.admin['school_id']},
            type: "GET", success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择分组</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    that.val(row.addresslv_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    }
});

$(document).on("change change2", "#c-communityCourse_id", function (e) {

    let that = $(this);
    if (e.type == "change2") {
        url = "/community/project/Setcourse/lists2?XDEBUG_SESSION_START=54354";
        $.ajax({
            url: url, //data: {cityId: Config.admin['city_id'], school_id: Config.admin['school_id']},
            type: "GET", success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择分组</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    that.val(row.communityCourse_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
                // 错误处理
            }
        });
    } else {

        if ($("#c-title").length > 0 && $("#c-title").val() == "") {
            $("#c-title").val($("#c-communityCourse_id option:selected").text());
        }
    }
});


$(document).on("change change2", "#c-column_id", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        url = "/column/column/lists?type=1"; // 修正URL路径
        $.ajax({
            url: url, type: "GET", dataType: "json", success: function (data) {
                if (!data) {
                    return;
                }
                var $column = that;
                $column.empty();
                $column.append('<option value="">请选择栏目</option>');
                var list = data;

                // 检查是否为社区管理员，如果是则只显示社区信息栏目
                var adminGroupId = getConfigAdmin('group_id', 0);
                var filteredList = list["list"] || list["data"] || list; // 支持多种数据格式

                if (adminGroupId == 8) {
                    // 社区管理员只能选择社区信息栏目
                    filteredList = list["list"].filter(function (column) {
                        // 去除前后空格进行比较
                        return column.name.trim() === '社区信息';
                    });
                } else if (adminGroupId == 3) {
                    // 学校管理员可以查看所有栏目，但可能需要根据学校过滤
                    // 这里可以根据需要添加学校特定的过滤逻辑
                }

                $.each(filteredList, function (index, column) {
                    $column.append('<option value="' + column.id + '">' + column.name + '</option>');
                });

                // 重新获取元素确保DOM已更新
                var $refreshedColumn = $('#c-column_id');

                // 强制刷新selectpicker（如果使用的话）
                if ($column.hasClass('selectpicker')) {
                    $column.selectpicker('refresh');
                }
                // 触发change事件确保其他依赖项更新
                $column.trigger('change');

                // 如果是社区管理员且只有一个社区信息栏目，自动选中
                if (adminGroupId == 8 && filteredList.length === 1) {
                    $column.val(filteredList[0].id);
                    $column.trigger('change');
                }

                if (row) {
                    that.val(row.column_id);
                    var text = $('#c-column_id>option:selected').text();
                    if (text == '师资队伍') {
                        $('#teacher-name-group').show();
                        $('#teacher-name-group').css("display", "block");
                        $('#c-name').attr('data-rule', 'required');
                        $('#c-name').val(row.name);
                    } else {
                        $('#teacher-name-group').hide();
                        $('#c-name').attr('data-rule', '');
                        $('#c-name').val('');
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
                // 错误处理
            }
        });
    }
});

$(document).on("change change2", "#c-school_id", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        let url = "";
        url = "/school/school/lists?XDEBUG_SESSION_START=54354";

        $.ajax({
            url: url,
            data: { cityId: getConfigAdmin('city_id'), school_id: getConfigAdmin('school_id') },
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if ($("#c-addresslv_id").length > 0) {
                    $("#c-addresslv_id").trigger("change2");
                }
                if ($("#c-subject_lv").length > 0) {
                    $("#c-subject_lv").trigger("change2");
                }

                if (row) {
                    if (e.target.id == "c-addresslv_id_tree") {
                        that.val(row.addresslv_id);
                    } else if (e.target.id == "c-school_id") {
                        that.val(row.school_id);
                    }

                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
        if ($("#c-addresslv_id3").length > 0) {
            $("#c-addresslv_id3").trigger("change3");
        }
        if ($("#c-subject_lv").length > 0) {
            $("#c-subject_lv").trigger("change2");
        }
        if ($("#c-qishu").length > 0) {
            if ($("#c-addresslv_id_tree").val() == "3" || $("#c-addresslv_id_tree").val() == "23") {
                $("#c-qishu").closest(".form-group").show();
            } else {
                $("#c-qishu").closest(".form-group").hide();
            }
        }
        if ($("#c-title").length > 0 && $("#c-title").val() == "") {
            $("#c-title").val(that.find("option:selected").text() + "轮播图");
        }
    }


    if ($("#c-addresslv_id").length > 0) {
        $("#c-addresslv_id").trigger("change2");
    }
    if ($("#c-addresslv_id3").length > 0) {
        $("#c-addresslv_id").trigger("change3");
    }


});

$(document).on("change change2", "#c-addresslv_id_tree", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        let url = "";
        url = "/school/school/lists2?XDEBUG_SESSION_START=54354";

        $.ajax({
            url: url,
            data: { cityId: getConfigAdmin('city_id'), school_id: getConfigAdmin('school_id') },
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if ($("#c-addresslv_id").length > 0) {
                    $("#c-addresslv_id").trigger("change2");
                }
                if ($("#c-subject_lv").length > 0) {
                    $("#c-subject_lv").trigger("change2");
                }

                if (row) {
                    if (e.target.id == "c-addresslv_id_tree") {
                        that.val(row.addresslv_id);
                    } else if (e.target.id == "c-school_id") {
                        that.val(row.school_id);
                    }

                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
        if ($("#c-addresslv_id3").length > 0) {
            $("#c-addresslv_id3").trigger("change3");
        }
        if ($("#c-subject_lv").length > 0) {
            $("#c-subject_lv").trigger("change2");
        }
        if ($("#c-qishu").length > 0) {
            if ($("#c-addresslv_id_tree").val() == "3" || $("#c-addresslv_id_tree").val() == "23") {
                $("#c-qishu").closest(".form-group").show();
            } else {
                $("#c-qishu").closest(".form-group").hide();
            }
        }
        if ($("#c-title").length > 0 && $("#c-title").val() == "") {
            $("#c-title").val(that.find("option:selected").text() + "轮播图");
        }
    }


    if ($("#c-addresslv_id").length > 0) {
        $("#c-addresslv_id").trigger("change2");
    }
    if ($("#c-addresslv_id3").length > 0) {
        $("#c-addresslv_id").trigger("change3");
    }


});


$(document).on("change change2", "#c-community_id", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/community/community/lists?XDEBUG_SESSION_START=54354",
            data: { cityId: getConfigAdmin('city_id'), district_id: getConfigAdmin('district_id') },
            type: "GET",
            success: function (data) {
                var $community = $('#c-community_id');
                $community.empty();
                $community.append('<option value="">请选择社区</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, community) {
                    $community.append('<option value="' + community.id + '">' + community.name + '</option>');
                });
                if ($("#c-addresslv_id").length > 0) {
                    $("#c-addresslv_id").trigger("change2");
                }
                if (row) {
                    that.val(row.community_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
    }
    if ($("#c-addresslv_id").length > 0) {
        $("#c-addresslv_id").trigger("change2");
    }
});

// 教学点下拉框数据加载
$(document).on("change change2", "#c-ocation_id", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        var admin = window.Config && window.Config.admin ? window.Config.admin : {};
        var ajaxData = {
            cityId: getConfigAdmin('city_id'), district_id: getConfigAdmin('district_id'), level: 1 // 只获取顶级教学点
        };
        // 仅社区管理员时带admin_id，但要确保管理员有权限
        if (admin.group_id == 8 && admin.id && admin.ocation_id) {
            ajaxData.admin_id = admin.id;
        }


        $.ajax({
            url: "/ocation/ocation/lists?XDEBUG_SESSION_START=54354",
            data: ajaxData,
            type: "GET",
            dataType: "json",
            success: function (data) {
                var $ocation = $('#c-ocation_id');
                $ocation.empty();
                $ocation.append('<option value="">请选择教学点</option>');
                var list = data.list || [];
                var selected = row && row.ocation_id ? row.ocation_id : [];
                // 确保selected始终是数组
                if (typeof selected === 'string' || typeof selected === 'number') {
                    selected = [selected];
                } else if (!Array.isArray(selected)) {
                    selected = [];
                }
                $.each(list, function (index, ocation) {
                    var sel = '';
                    try {
                        // 多重检查确保selected是数组且includes方法存在
                        if (Array.isArray(selected) && typeof selected.includes === 'function') {
                            sel = selected.includes(String(ocation.id)) ? ' selected' : '';
                        }
                    } catch (e) {
                        sel = '';
                    }
                    $ocation.append('<option value="' + ocation.id + '"' + sel + '>' + ocation.name + '</option>');
                });
                if (row) {
                    if (row.ocation_id) {
                        if (row.ocation_id != "") {
                            that.val(row.ocation_id);
                        } else if ($(that).data("default") > 0) {
                            that.val($(that).data("default"));
                            if ($('#c-image-width').length > 0 && $('#c-image-height').length > 0) {
                                var $selectedOption = $("#c-ocation_id").find('option:selected');
                                var imageWidth = $selectedOption.attr('data-image-width');
                                var imageHeight = $selectedOption.attr('data-image-height');

                                // 如果选中的option有宽高属性，则填入对应字段
                                if (imageWidth) {
                                    $('#c-image-width').val(imageWidth);
                                }
                                if (imageHeight) {
                                    $('#c-image-height').val(imageHeight);
                                }
                            }
                        }
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
                // 动态设置下拉框高度，最多20行
                var optionCount = list.length;
                var size = optionCount + 5;
                if (size > 20) size = 20;
                if (size < 5) size = 5;
                $ocation.attr('size', size);
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-title").length > 0) {
            if ($("#c-title").val() == "") {
                $("#c-title").val(that.find("option:selected").text() + "轮播图");
            }
        }
    }
});

$(document).on("change change2", "#c-ocation_id_sq", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        var admin = window.Config && window.Config.admin ? window.Config.admin : {};
        var ajaxData = {
            cityId: getConfigAdmin('city_id'), district_id: getConfigAdmin('district_id'), level: 1 // 只获取顶级教学点
        };
        // 仅社区管理员时带admin_id
        if (admin.group_id == 8 && admin.id) {
            ajaxData.admin_id = admin.id;
        }
        $.ajax({
            url: "/ocation/ocation/lists_sq?XDEBUG_SESSION_START=54354",
            data: ajaxData,
            type: "GET",
            dataType: "json",
            success: function (data) {
                var $ocation = $('#c-ocation_id_sq');
                $ocation.empty();
                $ocation.append('<option value="">请选择教学点</option>');
                var list = data.list || [];
                var selected = row && row.ocation_id ? row.ocation_id : [];
                // 确保selected始终是数组
                if (typeof selected === 'string' || typeof selected === 'number') {
                    selected = [selected];
                } else if (!Array.isArray(selected)) {
                    selected = [];
                }
                $.each(list, function (index, ocation) {
                    var sel = '';
                    try {
                        // 多重检查确保selected是数组且includes方法存在
                        if (Array.isArray(selected) && typeof selected.includes === 'function') {
                            sel = selected.includes(String(ocation.id)) ? ' selected' : '';
                        }
                    } catch (e) {
                        sel = '';
                    }
                    $ocation.append('<option value="' + ocation.id + '"' + sel + '>' + ocation.name + '</option>');
                });
                if (row) {
                    if (row.ocation_id) {
                        if (row.ocation_id != "") {
                            that.val(row.ocation_id);
                        } else if ($(that).data("default") > 0) {
                            that.val($(that).data("default"));
                            if ($('#c-image-width').length > 0 && $('#c-image-height').length > 0) {
                                var $selectedOption = $("#c-ocation_id").find('option:selected');
                                var imageWidth = $selectedOption.attr('data-image-width');
                                var imageHeight = $selectedOption.attr('data-image-height');

                                // 如果选中的option有宽高属性，则填入对应字段
                                if (imageWidth) {
                                    $('#c-image-width').val(imageWidth);
                                }
                                if (imageHeight) {
                                    $('#c-image-height').val(imageHeight);
                                }
                            }
                        }
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
                // 动态设置下拉框高度，最多20行
                var optionCount = list.length;
                var size = optionCount + 5;
                if (size > 20) size = 20;
                if (size < 5) size = 5;
                $ocation.attr('size', size);
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-title").length > 0) {
            if ($("#c-title").val() == "") {
                $("#c-title").val(that.find("option:selected").text() + "轮播图");
            }
        }
        // 新增功能：当#c-ocation_id_sq的值改变时，如果#c-name存在且为空，则设置其值
        if ($("#c-name").length > 0) {
            if ($("#c-name").val() == "") {
                // 获取选中选项的文本并清理特殊字符
                var selectedText = that.find("option:selected").text();
                // 去除开头的树型修改符号（通常是空格、横线、竖线等符号）
                selectedText = selectedText.replace(/^[|\s\-—_├└│]+/, '');
                // 去除括号及括号内的所有内容
                selectedText = selectedText.replace(/\(.*?\)/g, '');
                // 去除可能的多余空格
                selectedText = selectedText.trim();
                $("#c-name").val(selectedText + "社区班级");

                // AJAX获取社区班级数据并填充相关字段
                var selectedOcationId = that.val();
                if (selectedOcationId) {
                    $.ajax({
                        url: "/ocation/ocation/getCommunityClassInfo",
                        type: "GET",
                        data: { ocation_id: selectedOcationId },
                        dataType: "json",
                        success: function (response) {
                            if (response && response.data) {
                                // 填充班级管理员
                                if ($("#c-class_admin").length > 0 && response.data.class_admin) {
                                    $("#c-class_admin").val(response.data.class_admin);
                                }
                                // 填充班级头像
                                if ($("#c-class_avatar").length > 0 && response.data.class_avatar) {
                                    $("#c-class_avatar").val(response.data.class_avatar);
                                }
                                // 填充班级详细信息
                                if ($("#c-class_details").length > 0 && response.data.class_details) {
                                    $("#c-class_details").val(response.data.class_details);
                                }
                            }
                        },
                        error: function (xhr, status, error) {
                        }
                    });
                }
            }
        }
    }
});


$(document).on("change change2", "#c-ocation_id_community", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        var admin = window.Config && window.Config.admin ? window.Config.admin : {};
        var ajaxData = {
            cityId: getConfigAdmin('city_id'), district_id: getConfigAdmin('district_id'), level: 1 // 只获取顶级教学点
        };
        // 仅社区管理员时带admin_id
        if (admin.group_id == 8 && admin.id) {
            ajaxData.admin_id = admin.id;
        }
        $.ajax({
            url: "/ocation/ocation/lists_community?XDEBUG_SESSION_START=54354",
            data: ajaxData,
            type: "GET",
            dataType: "json",
            success: function (data) {
                var $ocation = $('#c-ocation_id_community');
                $ocation.empty();
                $ocation.append('<option value="">请选择教学点</option>');
                var list = data.list || [];
                var selected = row && row.ocation_id ? row.ocation_id : [];
                // 确保selected始终是数组
                if (typeof selected === 'string' || typeof selected === 'number') {
                    selected = [selected];
                } else if (!Array.isArray(selected)) {
                    selected = [];
                }
                $.each(list, function (index, ocation) {
                    var sel = '';
                    try {
                        // 多重检查确保selected是数组且includes方法存在
                        if (Array.isArray(selected) && typeof selected.includes === 'function') {
                            sel = selected.includes(String(ocation.id)) ? ' selected' : '';
                        }
                    } catch (e) {
                        sel = '';
                    }
                    $ocation.append('<option value="' + ocation.id + '"' + sel + '>' + ocation.name + '</option>');
                });
                if (row) {
                    that.val(row.ocation_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
                // 动态设置下拉框高度，最多20行
                var optionCount = list.length;
                var size = optionCount + 5;
                if (size > 20) size = 20;
                if (size < 5) size = 5;
                $ocation.attr('size', size);
            },
            error: function (xhr, status, error) {
            }
        });
    }
});

$(document).on("change change2", "#c-coursetype_tree", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/coursetype/coursetype/liststree?XDEBUG_SESSION_START=54354",
            type: "GET",
            dataType: "json",
            success: function (data) {
                debugger;
                var $coursetype = $('#c-coursetype_tree');
                $coursetype.empty();
                $coursetype.append('<option value="">请选择课程类型</option>');
                var list = data.list || [];
                var selected = row && row.coursetype_id ? row.coursetype_id : [];
                // 确保selected始终是数组
                if (typeof selected === 'string' || typeof selected === 'number') {
                    selected = [selected];
                } else if (!Array.isArray(selected)) {
                    selected = [];
                }
                $.each(list, function (index, coursetype) {
                    var sel = '';
                    try {
                        // 多重检查确保selected是数组且includes方法存在
                        if (Array.isArray(selected) && typeof selected.includes === 'function') {
                            sel = selected.includes(String(coursetype.id)) ? ' selected' : '';
                        }
                    } catch (e) {
                        sel = '';
                    }
                    $coursetype.append('<option value="' + coursetype.id + '"' + sel + '>' + coursetype.name + '</option>');
                });
                if (row) {
                    that.val(row.coursetype_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
            }
        });
    }
});

$(document).on("change change2 change3", "#c-subject_lv,#c-subject_lv2,#c-subject_lv2,#c-subjecct-lv3-pid", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let addressLv = getValue("addresslv_id");
    let subjectLv = getValue("subject_lv");

    if (!addressLv) {
        addressLv = getValue("address_lv");
    }
    if ($("#c-addresslv_id_tree").length > 0) {
        subjectLv = $("#c-addresslv_id_tree").val();
    }

    if ($("#c-subject_lv", window.parent.document).length > 0) {
        subjectLv = $("#c-subject_lv>option:selected", window.parent.document).val();
    }
    let that = $(this);
    if (e.type == "change2") {
        if (row && row.school_id) {
            schoolId = row.school_id;
        }
        if (row && row.addressLv) {
            addressLv = row.addressLv;
        }
        if (row && row.address_lv) {
            addressLv = row.address_lv;
        }
        if (row && row.addresslv_id) {
            addressLv = row.addresslv_id;
        }

        if ($("#c-subject_lv", window.parent.document).length > 0) {
            subjectLv = $("#c-subject_lv>option:selected", window.parent.document).val();
        } else if (row && row.subject_lv) {
            subjectLv = row.subject_lv ?? 30;
        } else {
            subjectLv = subjectLv ?? 30;
        }
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, address_lv: addressLv, subject_lv: subjectLv },

            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学科层级</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('subject_lv')) {
                        that.val(row.subject_lv);
                    } else if (row.hasOwnProperty('subjectlv')) {
                        that.val(row.subjectlv);
                    }
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else if (e.type == "change3") {
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学科层级</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('pid')) {
                        that.val(row.pid);
                    } else if (row.hasOwnProperty('subjectlv')) {
                        that.val(row.subjectlv);
                    }
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
    }
});


$(document).on("change change2", "#c-subject_lv_level", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let addressLv = getValue("addresslv_id");
    if (!addressLv) {
        addressLv = getValue("address_lv");
    }
    if ($("#c-addresslv_id_tree").length > 0) {
        addressLv = $("#c-addresslv_id_tree").val();
    }
    let that = $(this);
    if (e.type == "change2") {
        if (row && row.school_id) {
            schoolId = row.school_id;
        }
        if (row && row.addressLv) {
            addressLv = row.addressLv;
        }
        if (row && row.address_lv) {
            addressLv = row.address_lv;
        }
        if (row && row.addresslv_id) {
            addressLv = row.addresslv_id;
        }
        $.ajax({
            url: "/subjectlv/subjectlv/lists?level=1&XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学科层级</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('subject_lv')) {
                        that.val(row.subject_lv);
                    } else if (row.hasOwnProperty('subjectlv')) {
                        that.val(row.subjectlv);
                    }
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
    }
});

$(document).on("change change2", "#c-week", function (e) {
    if (row && row.week && e.type == "change2") {
        setTimeout(function () {
            $("#c-week").val(row.week);
            $("#c-daytime").trigger("change2");
        }, 1000); // 2000 毫秒即 2 秒
    }
    if ($("#c-daytime").length > 0) {
        hasdaytime();
    }
});
$(document).on("change change2", "#c-daytime", function (e) {
    if (row && row.daytime && e.type == "change2") {
        setTimeout(function () {
            $("#c-daytime").val(row.daytime);
            $("#c-daytime option:selected").attr("disabled", false);
            $("#c-daytime option:selected").text($("#c-daytime option:selected").text().replace(/\(.*\)/gi, ""));
        }, 1000); // 2000 毫秒即 2 秒
    }
});


$(document).on("change change2", "#c-class_type", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let addressLv = getValue("addresslv_id");
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/subjectlv/subjectlv/class_type?XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择课程类型</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('class_type')) {
                        that.val(row.class_type);
                    } else if (row.hasOwnProperty('class_type')) {
                        that.val(row.class_type);
                    }
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {

    }
});

$(document).on("change change2", "#c-classes_type", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let addressLv = getValue("addresslv_id");
    let classes_type = getValue("classes_type");
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/classes/classes/classes_type?XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择班级类型</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (classes_type) {
                    that.val(classes_type);
                } else if (row) {
                    if (row.hasOwnProperty('classes_type')) {
                        that.val(row.classes_type);
                    } else if (row.hasOwnProperty('classes_type')) {
                        that.val(row.classes_type);
                    }
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {

    }
});

$(document).on("change change2 change3 change4", "#c-address_lv,#c-addresslv_id,#c-address_lv3,#c-addresslv_id3,#c-addresslv_id4,#c-address_lv_pid", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let relType = getValue("rel_type");
    let relId = getValue("rel_id");
    let addressLv = getValue("addresslv_id");
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/addresslv/addresslv/lists?XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, relType: relType, relId: relId, address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = that;
                var disabled = "";
                $school.empty();
                $school.append('<option value="">请选择学校</option>');

                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    if (that.attr("id") == "c-addresslv_id4") {
                        $school.append('<option value="' + school.subject_id + '"' + disabled + ' parent="' + school.parent + '" level="' + school.level + '">' + school.name + '</option>');
                    } else {
                        $school.append('<option value="' + school.id + '"' + disabled + ' parent="' + school.parent + '" level="' + school.level + '">' + school.name + '</option>');
                    }
                });
                if ($("#province_id").length > 0) {
                    $("#province_id").val(school.province_id);
                }
                // if ($("#c-city_id").length > 0) {
                //     $("#c-city_id").val(school.city_id);
                // }
                // if ($("#c-district_id").length > 0) {
                //     $("#c-district_id").val(school.district_id);
                // }
                if ($("#c-addresslv_id3").length > 0) {
                    $("#c-addresslv_id3").val(school.addresslv_id);
                }
                if (row) {
                    if (row.hasOwnProperty('addresslv_id')) {
                        that.val(row.addresslv_id);
                    } else if (row.hasOwnProperty('address_lv')) {
                        that.val(row.address_lv);
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }

            },
            error: function (xhr, status, error) {
            }
        });
    } else if (e.type == "change3") {
        $.ajax({
            url: "/addresslv/addresslv/lists?XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, relType: relType, relId: relId, address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = that;
                var disabled = "";
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '"' + disabled + ' parent="' + school.parent + '" level="' + school.level + '">' + school.name + '</option>');
                });
                if ($("#province_id").length > 0) {
                    $("#province_id").val(school.province_id);
                }
                if ($("#c-city_id").length > 0) {
                    $("#c-city_id").val(school.city_id);
                }
                if ($("#c-district_id").length > 0) {
                    $("#c-district_id").val(school.district_id);
                }
                if ($("#c-subjecct-lv3-pid").length > 0) {
                    $("#c-subjecct-lv3-pid").trigger("change3");
                }
                if (row) {
                    that.val(row.address_lv);
                    if ($("#c-address_lv_octionlevel").length > 0) {
                        $("#c-address_lv_octionlevel").val(row.address_lv_octionlevel);
                    }
                    if ($("#c-pid").length > 0) {
                        $("#c-pid").val(row.pid);
                    }
                }

                if ($("#c-address_lv_octionlevel").length > 0) {
                    //$("#c-address_lv_octionlevel").removeClass("readonly-select");
                    if ($("#c-ocation_pid").length > 0) {
                        level = $("#c-ocation_pid option:selected").attr("level");
                        $("#c-address_lv_octionlevel").find("option").each(function () {
                            if ($(this).attr("value") < level + 1) {
                                $(this).hide();
                            }
                        });
                    }

                    if ($("#c-address_lv_octionlevel").val() == 1) {
                        $("#c-starttime,#c-endtime").closest("div.form-group").hide();
                        $("#c-entvirt").closest("div.form-group").hide();
                    } else if ($("#c-address_lv_octionlevel").val() > 1) {
                        $("#c-starttime,#c-endtime").closest("div.form-group").show();
                    }
                    // 实体虚拟字段只在教学点等级为2时显示
                    if ($("#c-address_lv_octionlevel").val() == 2) {
                        $("#div-entvirt").closest("div.form-group").show();
                    } else {
                        $("#div-entvirt").closest("div.form-group").hide();
                    }
                    // 教室类型只在教学点等级为"上课教室"(值为4)时显示
                    if ($("#c-address_lv_octionlevel").val() == 4) {
                        $("#div-ocation_type").closest("div.form-group").show();
                    } else {
                        $("#div-ocation_type").closest("div.form-group").hide();
                    }


                    //$("#c-address_lv_octionlevel").addClass("readonly-select");//pointer-events: none

                    //$("#c-ocation_pid").removeClass("readonly-select");
                }
                if (row) {
                    that.val(row.address_lv);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }

            },
            error: function (xhr, status, error) {
            }
        });
    } else if (e.type == "change4") {
        $.ajax({
            url: "/addresslv/addresslv/lists?XDEBUG_SESSION_START=54354",
            data: { cityId: cityId, school_id: schoolId, relType: relType, relId: relId, address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = that;
                var disabled = "";
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.level > 1) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + ' subjectlv_id="' + school.subject_id + '" parent="' + school.name + '" level="' + school.level + '">' + school.name + '</option>');
                });
                // 修复：添加缺失的闭合标签
                if ($("#province_id").length > 0) {
                    $("#province_id").val(school.province_id);
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
    }
});

$(document).on("change change2,change3", "#c-pid,#c-subjecct-lv3-pid", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let relType = getValue("rel_type");
    let relId = getValue("rel_id");
    let addressLv = getValue("address_lv");
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=54354",
            data: { cityId: getConfigAdmin('city_id'), school_id: $("#c-school_id").val(), address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = $("#c-pid");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row && row.receiver_id) {
                    // 处理多选回显：如果receiver_id是数组，直接设置；如果是字符串，先转换为数组
                    var receiverIds = Array.isArray(row.receiver_id) ? row.receiver_id : row.receiver_id.split(',');
                    that.val(receiverIds);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else if (e.type == "change3") {
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=11111",
            data: { cityId: getConfigAdmin('city_id'), school_id: $("#c-school_id").val(), address_lv: addressLv },
            type: "GET",
            success: function (data) {
                var $school = $("#c-pid,#c-subjecct-lv3-pid");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('addresslv_id')) {
                        that.val(row.addresslv_id);
                    } else if (row.hasOwnProperty('address_lv')) {
                        that.val(row.address_lv);
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
            }
        });
    } else {

    }
});


$(document).on("change change2", "#c-user_id", function (e) {
    if (e.type == "change2") {
        var $userSelect = $("#c-user_id");
        $userSelect.empty();
        $userSelect.append('<option value="">请选择用户</option>');

        $.ajax({
            url: "/user/user/lists", data: {
                cityId: getConfigAdmin('city_id', ''),
                school_id: $("#c-school_id").val() || '',
                community_id: $("#c-community_id").val() || '',
                classes_id: $("#c-classes_id").val() || '',
            }, type: "GET", success: function (data) {
                var list = JSON.parse(data);
                $.each(list["list"], function (index, user) {
                    $userSelect.append('<option value="' + user.id + '">' + user.text + '</option>');
                });
            }, error: function (xhr, status, error) {
            }
        });
    } else {
        // change事件处理
    }
});

$(document).on("change change2", "#c-teacher_id", function (e) {
    if (e.type == "change2") {
        $.ajax({
            url: "/user/user/lists?XDEBUG_SESSION_START=54354", data: {
                cityId: getConfigAdmin('city_id'),
                school_id: $("#c-school_id").val() || 0,
                community_id: $("#c-community_id").val() || 0,
            }, type: "GET", success: function (data) {
                var $school = $("#c-teacher_id");
                $school.empty();
                var list = JSON.parse(data);

                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.value + '">' + school.text + '</option>');
                });
                // if (row) {
                //     that.val(row.ocation_id);
                // } else if (that.find("option").length == 2) {
                //     that.find("option").each(function () {
                //         var value = $(this).val();
                //         if (value !== "" && value !== "0") {
                //             $(this).prop("selected", true);
                //             return false;
                //         }
                //     });
                // }
            }, error: function (xhr, status, error) {
            }
        });
    } else {

    }
});

$(document).on("change change2", "#c-message_type", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/category/typelist", data: {
                type: "message"
            }, type: "GET", success: function (data) {
                var $messageType = that;
                $messageType.empty();
                $messageType.append('<option value="">请选择消息类型</option>');
                //var list = JSON.parse(data);
                $.each(data["data"], function (index, category) {
                    var selected = row && row.message_type == category.id ? ' selected' : '';
                    $messageType.append('<option value="' + category.id + '"' + selected + '>' + category.name + '</option>');
                });
            }, error: function (xhr, status, error) {
            }
        });
    } else {
        // change事件处理
    }
});

$(document).on("change change2", "#c-course_id", function (e) {
    let that = $(this);
    if (e.type == "change2") {

        $.ajax({
            url: "/column/column/getcolumns", data: { pid: 13 }, type: "GET", dataType: "json", success: function (data) {
                var $course = that;
                $course.empty();
                $course.append('<option value="">请选择课程</option>');
                var list = data;
                $.each(list["data"], function (index, course) {
                    $course.append('<option value="' + course.id + '">' + course.column + '</option>');
                });
                if (row) {
                    that.val(row.course_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    }
});

//--------------------------教学点等级----------------------
$(document).on("change change2", "#c-address_lv_octionlevel", function (e) {

    let that = $(this);
    if (e.type == "change2") {
        // 获取row数据
        var row = $('#row').val();
        if (row) {
            if (typeof row == "string") {
                row = JSON.parse(row);
            }
        }
        if (row) {
            that.val(row.address_lv);
            if ($("#c-address_lv_octionlevel").length > 0) {
                $("#c-address_lv_octionlevel").val(row.address_lv_octionlevel);
            }
            if ($("#c-pid").length > 0) {
                $("#c-pid").val(row.pid);
            }
        }
    }
});

$(document).on("change2 change", "#c-receiver_id", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/ocation/ocation/listsusers?XDEBUG_SESSION_START=54354", data: {
                ocation_id: $("#c-ocation_id").val()
            }, type: "GET", success: function (data) {
                var $ocation = that;
                $ocation.empty();
                var list = JSON.parse(data);
                var addedValues = []; // 用于跟踪已添加的值，实现去重
                $.each(list["list"], function (index, ocation) {
                    // 排重：ocation.id相同的只能出现一次
                    if (addedValues.indexOf(ocation.id) !== -1) {
                        return; // 跳过重复的值
                    }
                    addedValues.push(ocation.id);

                    // 修改：只有当octionlevel==5时才可选，其他不可选
                    if (ocation.address_lv_octionlevel != 5) {
                        disabled = " disabled='disabled'";
                    } else {
                        disabled = "";
                    }
                    var style = ocation.address_lv_octionlevel == 5 ? ' style="background-color: #e8f5e8; color: #2d5a2d; font-weight: bold;"' : '';
                    $ocation.append('<option value="' + ocation.id + '"' + disabled + style + ' parent="' + ocation.parent + '" level="' + ocation.level + '" octionlevel="' + ocation.address_lv_octionlevel + '">' + ocation.name + '</option>');
                });
                if (row && row.receiver_id) {
                    // 处理receiver_id的多选回显
                    var receiverIds = [];
                    if (typeof row.receiver_id === 'string') {
                        // 如果是逗号分隔的字符串，转换为数组
                        receiverIds = row.receiver_id.split(',').filter(function (id) {
                            return id.trim() !== '';
                        });
                    } else if (Array.isArray(row.receiver_id)) {
                        // 如果已经是数组，直接使用
                        receiverIds = row.receiver_id;
                    }
                    that.val(receiverIds);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    }
});

$(document).on("change2 change", "#c-user_id2", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/ocation/ocation/listsusers?XDEBUG_SESSION_START=54354", data: {
                ocation_id: $("#c-ocation_id").val()
            }, type: "GET", success: function (data) {
                var $ocation = that;
                $ocation.empty();
                var list = JSON.parse(data);
                var addedValues = []; // 用于跟踪已添加的值，实现去重
                $.each(list["list"], function (index, ocation) {
                    // 排重：ocation.id相同的只能出现一次
                    if (addedValues.indexOf(ocation.id) !== -1) {
                        return; // 跳过重复的值
                    }
                    addedValues.push(ocation.id);

                    // 修改：只有当octionlevel==5时才可选，其他不可选
                    if (ocation.address_lv_octionlevel != 5) {
                        disabled = " disabled='disabled'";
                    } else {
                        disabled = "";
                    }
                    var style = ocation.address_lv_octionlevel == 5 ? ' style="background-color: #e8f5e8; color: #2d5a2d; font-weight: bold;"' : '';

                    // 提取纯数字ID，如果ocation.id是'student_59'格式，则提取59
                    var userId = ocation.id;
                    if (typeof userId === 'string' && userId.includes('_')) {
                        userId = userId.split('_')[1]; // 提取下划线后的数字部分
                    }
                    // 确保是数字
                    userId = parseInt(userId) || ocation.id;

                    $ocation.append('<option value="' + userId + '"' + disabled + style + ' parent="' + ocation.parent + '" level="' + ocation.level + '" octionlevel="' + ocation.address_lv_octionlevel + '">' + ocation.name + '</option>');
                });
                if (row && row.receiver_id) {
                    // 处理receiver_id的多选回显
                    var receiverIds = [];
                    if (typeof row.receiver_id === 'string') {
                        // 如果是逗号分隔的字符串，转换为数组
                        receiverIds = row.receiver_id.split(',').filter(function (id) {
                            return id.trim() !== '';
                        });
                    } else if (Array.isArray(row.receiver_id)) {
                        // 如果已经是数组，直接使用
                        receiverIds = row.receiver_id;
                    }
                    that.val(receiverIds);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    }
});

$(document).on("change2 change", "#c-ocation_pid", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/ocation/ocation/lists2?XDEBUG_SESSION_START=54354", data: {
                cityId: getConfigAdmin('city_id'),
                relType: Config.relType ? Config.relType : getConfigAdmin('rel_type'),
                relId: Config.relId ? Config.relId : getConfigAdmin('rel_id'),
                addresslv_id: $("#c-address_lv").val()
            }, type: "GET", success: function (data) {
                var $ocation = that;
                $ocation.empty();
                var list = JSON.parse(data);
                var addedValues = []; // 用于跟踪已添加的值，实现去重
                $.each(list["all"]["list"], function (index, ocation) {
                    // 排重：ocation.id相同的只能出现一次
                    if (addedValues.indexOf(ocation.id) !== -1) {
                        return; // 跳过重复的值
                    }
                    addedValues.push(ocation.id);
                    disabled = "";
                    var style = ocation.address_lv_octionlevel == 5 ? ' style="background-color: #e8f5e8; color: #2d5a2d; font-weight: bold;"' : '';
                    $ocation.append('<option value="' + ocation.id + '"' + disabled + style + ' parent="' + ocation.parent + '" level="' + ocation.level + '" octionlevel="' + ocation.address_lv_octionlevel + '">' + ocation.name + '</option>');
                });
                if (row) {
                    that.val(row.pid);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    } else if (e.type == "change") {
        if ($("#c-ocation_pid").length > 0) {
            level = $("#c-ocation_pid option:selected").attr("address_lv_octionlevel");
            $("#c-address_lv_octionlevel").find("option").each(function () {
                if ($(this).attr("value") <= parseInt(level)) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
            $("#c-address_lv_octionlevel").val(parseInt(level) + 1);
        }
    }
});


$(document).on("click", "#c-ocation_class", function () {
    // 获取 select 和 input 元素
    const selectElement = $('#c-ocation_class');
    const that = $(this);

    // 更严格的剪贴板API检查
    if (navigator.clipboard &&
        typeof navigator.clipboard.readText === 'function' &&
        window.isSecureContext) {

        // 获取粘贴板上的内容
        navigator.clipboard.readText().then(text => {
            // 查找包含粘贴板内容的 option
            const options = that.find("option");
            let foundOption = null;

            options.each(function () {
                if ($(this).text().includes(text.trim())) {
                    foundOption = this;
                    return false; // 停止遍历
                }
            });

            // 如果找到匹配的 option，则选中它
            if (foundOption) {
                that.val(foundOption.value);
                that.focus();
            }
        }).catch(err => {
        });
    } else {
        // 剪贴板API不可用时的备选方案
    }
});

$(document).ready(function () {
    // 监听学员管理选项卡的点击事件
    $('a[href="#tabs_3"]').on('click', function () {
        const classId = new URLSearchParams(window.location.search).get('class_id') || $("#c-id").val();
        const url = Fast.api.fixurl('user/studentmanager/index?class_id=' + classId);

        // 设置全局变量供学员管理表格使用
        window.currentClassId = classId;
        const $content = $('#student-manager-content');

        // 检查是否已经加载过学员管理内容
        if ($content.hasClass('student-manager-loaded')) {
            return;
        }

        // 显示加载状态
        $content.html(`
            <div class="text-center" style="padding: 50px;">
                <i class="fa fa-spinner fa-spin fa-2x"></i>
                <p style="margin-top: 10px;">正在加载学员管理...</p>
            </div>
        `);

        // 先加载学员管理页面的HTML模板
        $.ajax({
            url: '/user/studentmanager/index?force_html=1',
            method: 'GET',
            dataType: 'html',
            cache: false,
            success: function (htmlResponse) {
                // 渲染HTML模板到页面

                // 验证响应内容，避免解析错误
                if (!htmlResponse || typeof htmlResponse !== 'string') {
                    $content.html('<div class="alert alert-danger">加载失败：响应内容无效</div>');
                    return;
                }

                try {
                    // 直接使用响应内容，让浏览器自动解析
                    $content.html(htmlResponse);

                    // 移除可能存在的操作按钮
                    $content.find('.btn-add, .btn-edit, .btn-del, .btn-import').remove();

                    // 设置加载标志，防止重复加载
                    $content.addClass('student-manager-loaded');
                } catch (error) {
                    $content.html('<div class="alert alert-danger">加载失败：HTML解析错误</div>');
                    return;
                }

                // 延迟初始化学员管理表格，确保DOM完全加载
                setTimeout(function () {
                    // 检查表格元素是否存在
                    var $table = $content.find('#table');

                    // 安全检查：确保 $content 存在且有 html() 方法
                    if (!$content || typeof $content.html !== 'function') {
                        return;
                    }

                    var contentHtml = $content.html();
                    if (contentHtml && typeof contentHtml === 'string') {
                        // HTML内容检查通过
                    } else {
                        return;
                    }

                    if ($table.length > 0) {

                        // 如果表格已经初始化过，先销毁它
                        if ($table.data('bootstrap.table')) {
                            $table.bootstrapTable('destroy');
                        }

                        // 设置class_id参数到全局，供student_manager.js使用
                        var classId = window.currentClassId || $('#c-id').val();
                        if (classId) {
                            window.studentManagerClassId = classId;
                        }

                        // 确保在正确的上下文中初始化表格
                        if (typeof require !== 'undefined') {
                            require(['user/studentmanager'], function (StudentManagerController) {
                                // 初始化学员管理表格
                                if (typeof StudentManagerController.index === 'function') {
                                    StudentManagerController.index();
                                } else if (typeof StudentManagerController.api !== 'undefined' && typeof StudentManagerController.api.bindevent === 'function') {
                                    StudentManagerController.api.bindevent();
                                }
                            });
                        }
                    }
                }, 800);
            },
            error: function (error) {
                // 处理请求错误
                $content.html(`
                    <div class="text-center" style="padding: 50px; color: red;">
                        <p>加载学员管理数据失败，请稍后重试。</p>
                        <button class="btn btn-primary btn-sm" onclick="location.reload()">刷新重试</button>
                    </div>
                `);
            }
        });
    });
});


$(document).on("click", "#c-classes_id", function () {
    const that = $(this);

    // 更严格的剪贴板API检查
    if (navigator.clipboard &&
        typeof navigator.clipboard.readText === 'function' &&
        window.isSecureContext) {

        // 获取粘贴板上的内容
        navigator.clipboard.readText().then(text => {
            // 查找包含粘贴板内容的 option
            const options = that.find("option");
            let foundOption = null;

            options.each(function () {
                if ($(this).text().includes(text.trim())) {
                    foundOption = this;
                    return false; // 停止遍历
                }
            });

            // 如果找到匹配的 option，则选中它
            if (foundOption) {
                that.val(foundOption.value);
                that.focus();
            }

        }).catch(err => {
            // 可以在这里添加用户提示
        });
    } else {
        // 剪贴板API不可用时的备选方案

        // 可选：提供手动输入的提示
        // alert('请手动选择或输入内容');
    }
});

$(document).on("change2 change", "#c-ocation_class", function (e) {
    let that = $(this);

    if (e.type == "change2") {

        $.ajax({
            url: "/ocation/ocation/lists2?XDEBUG_SESSION_START=54354", data: {
                cityId: getConfigAdmin('city_id'),
                relType: getConfigAdmin('rel_type'),
                relId: getConfigAdmin('rel_id'),
                addresslv_id: $("#c-address_lv").val()
            }, type: "GET", success: function (data, textStatus, jqXHR) {
                httpInfo(jqXHR, this);
                var $ocation = that;
                $ocation.empty();
                var list = JSON.parse(data);
                $.each(list["all"]["list"], function (index, ocation) {
                    disabled = (ocation.address_lv_octionlevel < 3 || typeof (ocation.address_lv_octionlevel) == 'undefined') ? " disabled  class='disabled'" : "";
                    checked = "";
                    // 根据$row是否有class_item元素来判断
                    if (row && row.class_items) {
                        var class_items = JSON.parse(row.class_items);
                        var hasMatch = false;
                        if (Array.isArray(class_items)) {
                            class_items.forEach(function (item) {
                                if (Array.isArray(item.teaching_point) && item.teaching_point.includes(ocation.id)) {
                                    hasMatch = true;
                                } else if (item.teaching_point == ocation.id) {
                                    hasMatch = true;
                                }
                            });
                        }
                        if (that && that.data("default") == ocation.id) {
                            checked = "selected";
                        }
                        if (hasMatch) {
                            checked = "selected";
                        }
                    } else {
                        // 原有的逻辑
                        if (row && Array.isArray(row.ocation_id)) {
                            checked = row.ocation_id.includes(ocation.id) ? "selected" : "";
                        } else if (row && row.ocation_id == ocation.id) {
                            checked = "selected";
                        } else if (that && that.data("default") == ocation.id) {
                            checked = "selected";
                        } else {
                            checked = "";
                        }
                    }

                    weekdays = ocation && ocation.weekdays ? " weekdays='" + ocation.weekdays + "'" : "";
                    schedule_data = ocation && ocation.schedule_data ? " schedule_data='" + ocation.schedule_data + "'" : "";
                    already_schedule = ocation && ocation.already_schedule ? " already_schedule='" + ocation.already_schedule + "'" : "";
                    disable_week_time = ocation && ocation.disable_week_time ? " disable_week_time='" + ocation.disable_week_time + "'" : "";
                    $ocation.append('<option value="' + ocation.id + '"' + weekdays + schedule_data + already_schedule + disable_week_time + disabled + ' ' + checked + ' ' + ' parent="' + ocation.parent + '" level="' + ocation.level + '">' + ocation.name + '</option>');
                });
                hasweek();
                hasdaytime();

                // 调整弹窗高度以适应新加载的内容
                adjustIframeHeight(100, 'c-ocation_class AJAX加载完成');
            }, error: function (xhr, status, error) {
            }
        });
    } else if (e.type == "change") {
        if ($("#c-ocation_pid").length > 0) {
            level = $("#c-ocation_class option:selected").attr("level");
            $("#c-address_lv_octionlevel").find("option").each(function () {
                if ($(this).attr("value") <= parseInt(level)) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
            $("#c-address_lv_octionlevel").val(parseInt(level) + 1);
        }
        hasweek();
        hasdaytime();


    }
});

function hasweek() {
    if ($("#c-week").length > 0) {
        var weekdays = $("#c-ocation_class option:selected").attr("weekdays");
        if (weekdays) {
            var weekdayArray = weekdays.split(',');
            var $weekSelect = $("#c-week");
            $weekSelect.empty(); // Clear existing options
            var weekdayMap = {
                '1': '周一', '2': '周二', '3': '周三', '4': '周四', '5': '周五', '6': '周六', '7': '周日'
            };

            weekdayArray.forEach(function (day) {
                if (weekdayMap[day]) {
                    $weekSelect.append($('<option>', {
                        value: day, text: weekdayMap[day]
                    }));
                }
            });

        }
    }
}

function hasdaytime() {
    if ($("#c-daytime").length > 0) {
        var scheduleData = $("#c-ocation_class option:selected").attr("schedule_data");
        var already_schedule = $("#c-ocation_class option:selected").attr("already_schedule");
        var disable_week_time = $("#c-ocation_class option:selected").attr("disable_week_time");
        //disable_week_time="周一 2节,周一 3节
        var week = $("#c-week option:selected").val();
        var ocation = $("#c-ocation_class option:selected").val();
        let already_scheduleArray = [];
        if (scheduleData) {
            try {
                var scheduleArray = JSON.parse(scheduleData);
                already_scheduleArray = JSON.parse(already_schedule);
                disable_week_timeArray = JSON.parse(disable_week_time);
                var $daytimeSelect = $("#c-daytime");
                $daytimeSelect.empty(); // Clear existing options
                for (let i = 0; i < scheduleArray.length; i++) {
                    const schedule = scheduleArray[i];
                    var optionText = schedule.start_time + '-' + schedule.end_time;
                    var optionValue = optionText;
                    if (already_scheduleArray[ocation] && already_scheduleArray[ocation][week]) {
                        if (already_scheduleArray[ocation][week].indexOf(optionText) !== -1) {
                            optionText += '(已被占用)';
                            $daytimeSelect.append($('<option>', {
                                value: optionValue, text: optionText, disabled: true // 设置为不可选状态
                            }));
                        } else {
                            $daytimeSelect.append($('<option>', {
                                value: optionValue, text: optionText
                            }));
                        }
                    } else if (disable_week_timeArray[ocation][week] && disable_week_timeArray[ocation][week].indexOf(optionText) !== -1) {
                        if (disable_week_timeArray[ocation][week].indexOf(optionText) !== -1) {
                            optionText += ' (周' + week + '这时间点该教室禁用)';
                            $daytimeSelect.append($('<option>', {
                                value: optionValue, text: optionText, disabled: true // 设置为不可选状态
                            }));
                        } else {
                            $daytimeSelect.append($('<option>', {
                                value: optionValue, text: optionText
                            }));
                        }
                    } else {
                        $daytimeSelect.append($('<option>', {
                            value: optionValue, text: optionText
                        }));
                    }
                }
                if (row && row.daytime && e.type == "change2") {
                    $("#c-daytime").val(row.daytime);
                    $("#c-daytime option:selected").removeAttr("disabled");
                    $("#c-daytime option:selected").text($("#c-daytime option:selected").text().replace(/\(.*\)/gi, ""));
                }
            } catch (e) {
            }
        }
    }
}

$(document).one("change change2", "#c-classes_id", function (e) {
    var that = $(this);

    if (e.type == "change2") {
        $.ajax({
            url: "/classes/classes/lists2?XDEBUG_SESSION_START=54354", data: {
                cityId: getConfigAdmin('city_id'),
                school_id: $("#c-school_id").val(),
                community_id: $("#c-community_id").val(),
                addresslv_id: $("#c-address_lv").val(),
                classes_id: $("#c-classes_id").val(),
                table_id: $("#c-table_id").data("default")>0?$("#c-table_id").data("default"):$("#c-table_id").val(),
                relType: getValue("rel_type"),
                relId: getValue("rel_id")
            }, type: "GET", success: function (data) {
                var $classes = $("#c-classes_id");
                $classes.empty();
                var list = JSON.parse(data);

                $.each(list["list"], function (index, classes) {
                    disabled = (classes.haschild < 3) ? " disabled  class='disabled'" : "";
                    checked = "";
                    debugger;
                    // 根据$row是否有class_item元素来判断
                    if (row && row.class_items) {
                        var class_items = JSON.parse(row.class_items);
                        var hasMatch = false;
                        if (Array.isArray(class_items)) {
                            class_items.forEach(function (item) {
                                if (item.class_id == classes.id) {
                                    hasMatch = true;
                                    checked = "selected";
                                }
                            });
                        }
                        var class_items2 = row.special_channel_classes.split(",");
                        if (Array.isArray(class_items2)) {
                            class_items2.forEach(function (item) {
                                if (item == classes.id) {
                                    hasMatch = true;
                                    checked = "selected";
                                }
                            });
                        }
                        if (that && that.data("default") == classes.id) {
                            checked = "selected";
                        }
                        if (hasMatch) {
                            checked = "selected";
                        }
                    } else if (row && row.classes_id) {
                        // 原有的逻辑
                        if (row && (Array.isArray(row.classes_id) ? row.classes_id.includes(classes.id) : row.classes_id == classes.id)) {
                            checked = "selected";
                        } else if (Config.classesName && (classes.name.includes(Config.classesName))) {
                            checked = "selected";
                        }
                    } else if (that && that.data("default") == classes.id) {
                        checked = "selected";
                    }

                    $classes.append('<option value="' + classes.id + '"' + disabled + ' ' + checked + ' ' + ' parent="' + classes.parent + '" level="' + classes.level + '" address_lv="' + classes.address_lv + '">' + classes.name + '</option>');
                });
                if ($("#c-student_id").length > 0) {
                    $("#c-student_id").trigger("change2");
                }

                if ($("#c-subject_lv").length > 0) {
                    $("#c-subject_lv").trigger("change2");
                }
                // 调整弹窗高度以适应新加载的内容
                adjustIframeHeight(100, 'c-classes_id AJAX加载完成');
            }, error: function (xhr, status, error) {
            }
        });
    } else {
        if ($('#c-address_lv').length > 0) {
            $("#c-address_lv").val($("#c-classes_id option:selected").attr("address_lv"));
        }
        if ($('#c-addresslv_id').length > 0) {
            $("#c-addresslv_id").val($("#c-classes_id option:selected").attr("address_lv"));
        }
        if ($('#c-subject_lv').length > 0) {
            $('#c-subject_lv').trigger("change2");
        }
        if ($("#c-student_id").length > 0) {
            $("#c-student_id").trigger("change2");
        }
        if ($("#c-title").length > 0 && $("#c-title").val() == "") {
            $("#c-title").val($("#c-classes_id option:selected").text());
        }
    }
});

$(document).on("change change2", "#c-student_id", function (e) {
    if (e.type == "change2") {
        $.ajax({
            url: "/classes/student/lists2?XDEBUG_SESSION_START=54354", data: {
                classes_id: $("#c-classes_id").val(),
            }, type: "GET", success: function (data) {
                var $students = $("#c-student_id");
                $students.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, classes) {
                    disabled = (classes.haschild < 3) ? " disabled  class='disabled'" : "";
                    checked = "";
                    if (row && (Array.isArray(row.student_id) ? row.student_id.includes(classes.id) : row.student_id == classes.id)) {
                        checked = "selected";
                    } else if (Config.classesName && (classes.name.includes(Config.classesName))) {
                        checked = "selected";
                    }

                    $students.append('<option value="' + classes.id + '"' + disabled + ' ' + checked + ' ' + ' parent="' + classes.parent + '" level="' + classes.level + '" address_lv="' + classes.address_lv + '">' + classes.name + '</option>');
                });

                // 调整弹窗高度以适应新加载的内容
                adjustIframeHeight(100, 'c-student_id AJAX加载完成');
            }, error: function (xhr, status, error) {
            }
        });
    }
});

// 添加 #c-cityarea_id 的监听事件，模拟 #c-column_id 的行为

$(document).on("change3", "#c-rel_type", function (e) {
    var $school = $("#c-rel_type");
    $school.empty();
    $school.append('<option value="1">学校</option>');
    $school.append('<option value="2">社区</option>');
    $school.append('<option value="3">其他机构</option>');
    $("#c-rel_type").trigger("change");
});

$(document).on("change change2", "#group", function (e) {
    var that = $("#c-rel_id");
    var selectedGroup = $(this).val();
    var selectedText = $(this).find("option:selected").text();

    // 隐藏所有相关表单组
    if ($("#c-school_id").length > 0) {
        $("#school-form-group").hide();
    }
    if ($("#c-community_id").length > 0) {
        $("#community-form-group").hide();
    }

    // 获取row数据
    var row = $('#row').val();
    if (row) {
        if (typeof row == "string") {
            row = JSON.parse(row);
        }
        that.val(row.group_id);
    }

    // 检查是否是学校管理员（ID=3或名称包含"学校"）
    if (selectedGroup == "3" || selectedText.indexOf("学校") !== -1) {
        $("#school-form-group").show();
        $("#community-form-group").hide();
        // 触发学校下拉框数据加载
        if ($("#c-school_id").length > 0) {
            $("#c-school_id").trigger("change2");
        }
    }
    // 检查是否是社区管理员（ID=8或名称包含"社区"）
    else if (selectedGroup == "8" || selectedText.indexOf("社区") !== -1) {
        $("#school-form-group").hide();
        $("#community-form-group").show();
        // 触发教学点下拉框数据加载
        if ($("#c-ocation_id").length > 0) {
            $("#c-ocation_id").trigger("change2");
        }
    } else {
        $("#school-form-group").hide();
        $("#community-form-group").hide();
    }

});

if ($('#c-pid').length > 0 && $('#h-rel_type').length > 0 && $('#h-rel_id').length > 0) {
    var $school = $('#c-pid');
    $school.empty();
    $school.append('<option value="">请选择父级</option>');
    $.ajax({
        url: "/addresslv/addresslv/lists",
        data: { relType: $("#h-rel_type").val(), relId: $("#h-rel_id").val(), cityId: Config.cityId },
        type: "GET",
        success: function (data) {
            var list = JSON.parse(data);
            $.each(list["list"], function (index, school) {
                $school.append('<option value="' + school.id + '">' + school.name + '</option>');
            });
            if (row) {
                that.val(row.pid);
            } else if (that.find("option").length == 2) {
                that.find("option").each(function () {
                    var value = $(this).val();
                    if (value !== "" && value !== "0") {
                        $(this).prop("selected", true);
                        return false;
                    }
                });
            }
        },
        error: function (xhr, status, error) {
        }
    });
}

function getAddress(point) {
    var geoc = new BMap.Geocoder();
    geoc.getLocation(point, function (result) {
        if (result) {
            var address = result.address; // 获取完整的地址信息
            $("#c-address").val(address); // 将地址信息写入 #address 元素
            var addressComponents = result.addressComponents;
            $("#city option:contains('" + addressComponents.city + "')").prop("selected", true);
            $("#county option:contains('" + addressComponents.district + "')").prop("selected", true);
        }
    });
}

function updateMap(type) {

    // 检查地图对象是否存在
    if (!window.map) {
        return;
    }

    // 检查districtCoordinates对象是否存在
    if (!window.districtCoordinates) {
        return;
    }

    // 检查BMap API是否可用
    if (typeof BMap === 'undefined') {
        return;
    }

    var selectedProvince = $("#c-cityarea_id option:selected").text();
    var selectedCity = $("#city option:selected").text();
    var selectedCounty = $("#county option:selected").text();
    var point = null;

    if (type == 1 && row && row.longitude > 0) {
        point = new BMap.Point(row.longitude, row.latitude);
    } else {
        // 添加更详细的检查
        if (selectedCounty && window.districtCoordinates[selectedProvince] && window.districtCoordinates[selectedProvince][selectedCounty]) {
            point = window.districtCoordinates[selectedProvince][selectedCounty];
} else if (selectedCity && window.districtCoordinates[selectedProvince] && window.districtCoordinates[selectedProvince][selectedCity] && window.districtCoordinates[selectedProvince][selectedCity][selectedCounty]) {
            // 修复：确保第三层对象存在
            point = window.districtCoordinates[selectedProvince][selectedCity][selectedCounty];
        } else if (window.districtCoordinates[selectedProvince]) {
            // 获取该省的第一个可用坐标点
            var provinceData = window.districtCoordinates[selectedProvince];
            var firstCity = Object.keys(provinceData)[0];
            if (firstCity && provinceData[firstCity]) {
                if (typeof provinceData[firstCity] === 'object' && provinceData[firstCity].lng && provinceData[firstCity].lat) {
                    point = provinceData[firstCity];
                } else if (typeof provinceData[firstCity] === 'object') {
                    // 如果是城市对象，获取其第一个区域
                    var firstArea = Object.keys(provinceData[firstCity])[0];
                    if (firstArea && provinceData[firstCity][firstArea]) {
                        point = provinceData[firstCity][firstArea];
                    }
                }
            }
        }
    }

    if (point) {
        $("#c-latitude").val(point.lat);
        $("#c-longitude").val(point.lng);
    }

    if (window.marker) {
        window.map.removeOverlay(window.marker);
    }

    try {
        // 添加更严格的检查
        if (window.map && typeof window.map.clearOverlays === 'function') {
            window.map.clearOverlays();
            window.map.centerAndZoom(point, 20);
            window.marker = new BMap.Marker(point);
            window.map.addOverlay(window.marker);
        }
    } catch (error) {
        // 不重新抛出错误，避免中断其他功能
    }
}

function geocoderSearch(address) {
    // 检查地图对象是否存在
    if (!window.map) {
        return;
    }

    var myGeo = new BMap.Geocoder();
    myGeo.getPoint(address, function (point) {
        if (point) {
            if (window.marker) {
                window.map.removeOverlay(window.marker);
            }
            window.map.clearOverlays(); // 清除之前的标注
            window.map.centerAndZoom(point, 15); // 调整缩放级别
            window.marker = new BMap.Marker(point);
            window.map.addOverlay(window.marker);
            $("#c-latitude").val(point.lat);
            $("#c-longitude").val(point.lng);
            myGeo.getLocation(point, function (result) {
                var addressComponents = result.addressComponents;
                $("#city option:contains('" + addressComponents.city + "')").prop("selected", true);
                $("#county option:contains('" + addressComponents.district + "')").prop("selected", true);
            });
        } else {
            alert("未找到该地址，请检查输入是否正确。");
        }
    }, "中国");
}


// 获取所有的 weekday 复选框 - 防止重复声明
if (typeof weekdaysCheckboxes === 'undefined') {
    var weekdaysCheckboxes = document.querySelectorAll('input[name="row[weekdays][]"]');
}
// 获取所有的 daytime 复选框 - 防止重复声明
if (typeof daytimeCheckboxes === 'undefined') {
    var daytimeCheckboxes = document.querySelectorAll('input[name="row[daytime][]"]');
}
// 获取 DisableWeekRange 下拉列表 - 防止重复声明
if (typeof disableWeekRange === 'undefined') {
    var disableWeekRange = document.getElementById('DisableWeekRange');
}
// 获取 schedule-table-container 中的所有行 - 防止重复声明
if (typeof scheduleTableRows === 'undefined') {
    var scheduleTableRows = $('#schedule-table-container tr');
}
// 获取 DisableWeekTime 下拉列表 - 防止重复声明
if (typeof disableWeekTime === 'undefined') {
    var disableWeekTime = $('#DisableWeekTime');
}

// 根据 weekday 值获取对应的文本
function getWeekdayText(weekday) {
    switch (weekday) {
        case '1':
            return '周一';
        case '2':
            return '周二';
        case '3':
            return '周三';
        case '4':
            return '周四';
        case '5':
            return '周五';
        case '6':
            return '周六';
        case '7':
            return '周日';
        default:
            return '';
    }
}

// 根据 daytime 值获取对应的文本
function getDaytimeText(daytime) {
    switch (daytime) {
        case '1':
            return '上午';
        case '2':
            return '中午';
        case '3':
            return '下午';
        case '4':
            return '晚上';
        default:
            return '';
    }
}

// 根据 lesson 值获取对应的文本
function getLessonText(lesson) {
    return `第${lesson}节课`;
}

// 生成选项并添加到下拉列表中
function addOptionsToSelect(select, options) {
    $(select).empty();
    options.forEach(option => {
        $(select).append(option);
    });
}

// 初始化 DisableWeekRange 下拉列表
function initDisableWeekRange() {
    const options = [];
    weekdaysCheckboxes.forEach(checkbox => {
        if (checkbox.checked) {

            const weekday = checkbox.value;
            const weekdayText = getWeekdayText(weekday);
            daytimeCheckboxes.forEach(checkbox2 => {
                if (checkbox2.checked) {
                    const daytime = checkbox2.value;
                    const daytimeText = getDaytimeText(daytime);
                    const option = $('<option>');
                    option.val(`${weekdayText} ${daytimeText}`);
                    option.text(`${weekdayText} ${daytimeText}`);
                    if (row && row.disable_week_range && row.disable_week_range.includes(`${weekdayText} ${daytimeText}`)) {
                        option.attr("selected", "selected");
                    }
                    options.push(option);
                }
            });
        }
    });
    if ($('#DisableWeekRange').length > 0) {
        addOptionsToSelect(disableWeekRange, options);
    }
}

// 初始化 DisableWeekTime 下拉列表
function initDisableWeekTime() {
    const options = [];
    weekdaysCheckboxes.forEach(checkbox => {
        if (checkbox.checked) {
            const weekday = checkbox.value;
            const weekdayText = getWeekdayText(weekday);
            $('#schedule-table-container').find("tr:gt(0)").each((index, row2) => {
                const lessonText = $(row2).find("input[name=oindex]").attr("value");
                const option = $('<option>');
                option.val(`${weekdayText} ${lessonText}节`);
                option.text(`${weekdayText} ${lessonText}节`);
                if (row && row.disable_week_time && row.disable_week_time.includes(`${weekdayText} ${lessonText}节`)) {
                    option.attr("selected", "selected");
                }
                options.push(option);
            });
        }
    });
    if ($('#DisableWeekTime').length > 0) {
        addOptionsToSelect(disableWeekTime, options);
    }
}

// 监听 weekday 和 daytime 复选框的变化
weekdaysCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', initDisableWeekRange);
    checkbox.addEventListener('change', initDisableWeekTime);
});
daytimeCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', initDisableWeekRange);
    checkbox.addEventListener('change', initDisableWeekTime);
});

// 监听 schedule-table-container 中的行变化
scheduleTableRows.on('DOMSubtreeModified', initDisableWeekTime);

// 初始化 DisableWeekRange 和 DisableWeekTime 下拉列表
setTimeout(initDisableWeekRange, 500);
setTimeout(initDisableWeekTime, 1500);


$(document).on("change change2", "#c-table_id", function (e) {
    that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/courset/coursetable/lists?XDEBUG_SESSION_START=54354", data: {
                cityId: Config.admin['city_id'],
                school_id: $("#c-school_id").val(),
                community_id: $("#c-community_id").val(),
                addresslv_id: $("#c-address_lv").val()
            }, type: "GET", success: function (data) {
                var $school = $("#c-table_id");
                $school.empty();
                var list = JSON.parse(data);
                $school.append('<option value="-1">请选择</option>');
                if (list["list"].length === 1) {
                    const school = list["list"][0];
                    $school.append('<option value="' + school.id + '" selected>' + school.name + '</option>');
                } else {
                    $.each(list["list"], function (index, school) {
                        $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                    });
                }
                $school.append('<option value="-9">(创建新项目/课程)</option>');
                row = $('#row').val();
                if (row) {
                    if (typeof row == "string") {
                        row = JSON.parse(row);
                    }
                    if (typeof row == "string") {
                        row = JSON.parse(row);
                    }
                    // 添加安全检查，确保row[0]存在且有table_id属性
                    if (row && row[0] && row[0].table_id) {
                        that.val(row[0].table_id);
                        //触发initTimeSchedules方法
                        initTimeSchedules();
                    }else if ($("#c-table_id").data("default")>0) {
                        $("#c-table_id").val($("#c-table_id").data("default"));
                    }else if (row && row.table_id) {
                        $("#c-table_id").val(row.table_id);
                    }
                    if($("#c-classes_id").length > 0){
                        $("#c-classes_id").trigger("change2");
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    } else {
        if ($("#c-table_id").val() == -9) {
            // 弹出新建项目课程的窗口 /coursetable/coursetable/add
            // 使用layer.open在当前窗口上方打开
            layer.open({
                type: 2,
                title: '新建项目课程',
                shadeClose: false,
                shade: 0.8,
                area: ['90%', '90%'],
                offset: '50px', // 在当前窗口上方显示
                content: '/coursetable/coursetable/add',
                zIndex: 999999,
                end: function () {
                    // 关闭后刷新下拉框
                    $("#c-table_id").trigger("change2");
                }
            });
        }

        if($("input[name='row[title]']").length > 0){
            $.ajax({
                url: "/coursetable/coursetable/tableDetail?XDEBUG_SESSION_START=54354", data: {
                    id: $("#c-table_id").val(),
                }, type: "GET", success: function (data) {
                    if (data != null && data != "") {
                        var data2 = JSON.parse(data);
                        if (data2.data) {
                            if ( $("input[name='row[title]']").length > 0&&$("input[name='row[title]']").val()==="") {
                                $("input[name='row[title]']").val(data2.data.project_name);
                            }
                            if ($("input[name='row[cover]']").length > 0&&$("input[name='row[cover]']").val()==="") {
                                $("input[name='row[cover]']").val(data2.data.cover);
                            }
                            if ($("input[name='row[start_time]']").length > 0&&$("input[name='row[start_time]']").val()==="") {
                                $("input[name='row[start_time]']").val(data2.data.start_date);
                            }
                            if ($("input[name='row[end_time]']").length > 0&&$("input[name='row[end_time]']").val()==="") {
                                $("input[name='row[end_time]']").val(data2.data.end_date);
                            }
                            if ($("input[name='row[max_num]']").length > 0&&$("input[name='row[max_num]']").val()==="") {
                                $("input[name='row[max_num]']").val(data2.data.num);
                            }
                            if ($("textarea[name='row[intro]']").length > 0&&$("textarea[name='row[intro]']").val()==="") {
                                $("textarea[name='row[intro]']").val(data2.data.intro);
                            }
                        }
                    }
                }, error: function (xhr, status, error) {
                }, complete: function (xhr, status) {
                    var ajaxConfig = this; // 保存AJAX配置对象
                    var curlCommand = 'curl -X GET "' + ajaxConfig.url + '"';
                    if (ajaxConfig.data && Object.keys(ajaxConfig.data).length > 0) {
                        curlCommand += ' -G';
                        for (var key in ajaxConfig.data) {
                            curlCommand += ' --data-urlencode "' + key + '=' + ajaxConfig.data[key] + '"';
                        }
                    }
                }
            });
        }
    }
});

$(document).on("change change2", "#c-publicwelfare_id", function (e) {
    that = $(this);

    if (e.type == "change2") {
        $.ajax({
            url: "/publicwelfare/publicwelfare/lists?XDEBUG_SESSION_START=54354", data: {
                cityId: Config.admin['city_id'],
                school_id: $("#c-school_id").val(),
                community_id: $("#c-community_id").val(),
                addresslv_id: $("#c-address_lv").val()
            }, type: "GET", success: function (data) {
                var $school = $("#c-publicwelfare_id");
                $school.empty();
                var list = (typeof data === 'string') ? JSON.parse(data) : data;
                // $school.append('<option value="-1">请选择</option>');
                if (list["list"].length === 1) {
                    const school = list["list"][0];
                    $school.append('<option value="' + school.id + '" selected>' + school.name + '</option>');
                } else {
                    $.each(list["list"], function (index, school) {
                        $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                    });
                }
                // 获取row数据
                var row = $('#row').val();
                if (row) {
                    if (typeof row == "string") {
                        row = JSON.parse(row);
                    }
                    that.val(row.publicwelfare_id || row.table_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    }
});


$(document).ready(function () {
    if ($('#c-latitude').length > 0) {
        if ($('#map').length > 0) {
            var mapContainer = $('#map');

            // 强制设置地图容器尺寸和样式
            mapContainer.css({
                'min-width': '400px',  // 添加最小宽度
                'height': '300px',
                'border': '1px solid #ccc',
                'background-color': '#f5f5f5',
                'display': 'block',
                'visibility': 'visible',
                'position': 'relative',  // 确保定位正确
                'overflow': 'hidden'     // 防止内容溢出
            });

            // 确保父级容器也有正确的样式
            mapContainer.parent().css({
                'display': 'block', 'visibility': 'visible', 'min-width': '400px'
            });

            // 强制重新计算布局
            mapContainer[0].offsetHeight;

            // 延迟初始化地图，确保容器尺寸已正确设置
            setTimeout(function () {
                if (typeof BMap !== 'undefined') {
                    // 再次检查容器尺寸

                    // 如果宽度仍然异常，强制设置固定宽度
                    if (mapContainer.width() <= 0) {
                        mapContainer.css('width', '600px');
                    }

                    window.map = new BMap.Map("map");
                    var point = new BMap.Point(108.35528924434603, 22.829188250573992); // 南宁市坐标
                    window.map.centerAndZoom(point, 12);
                    window.map.enableScrollWheelZoom(true);
                    // 强制重新渲染地图
                    setTimeout(function () {
                        window.map.getViewport();
                    }, 100);

                    // 添加点击事件
                    window.map.addEventListener("click", function (e) {
                        var lng = e.point.lng;
                        var lat = e.point.lat;
                        $('#c-longitude').val(lng);
                        $('#c-latitude').val(lat);

                        if (window.marker) {
                            window.map.removeOverlay(window.marker);
                        }
                        window.marker = new BMap.Marker(new BMap.Point(lng, lat));
                        window.map.addOverlay(window.marker);

                        getAddress(new BMap.Point(lng, lat));
                    });

                    // 检查是否有已存在的经纬度数据
                    var lng = $('#c-longitude').val();
                    var lat = $('#c-latitude').val();
                    if (lng && lat) {
                        var existingPoint = new BMap.Point(lng, lat);
                        window.map.centerAndZoom(existingPoint, 15);
                        var existingMarker = new BMap.Marker(existingPoint);
                        window.map.addOverlay(existingMarker);
                        window.marker = existingMarker;
                    }

                    // 保留原有的地址搜索功能
                    window.districtCoordinates = {
                        "广西壮族自治区": {
                            "南宁市": {
                                "": new BMap.Point(108.35528924434603, 22.829188250573992),
                                "市级": new BMap.Point(108.35528924434603, 22.829188250573992),
                                "青秀区": new BMap.Point(108.35528924434603, 22.829188250573992),
                                "兴宁区": new BMap.Point(108.3313, 22.8404),
                                "西乡塘区": new BMap.Point(108.2729, 22.8567),
                                "江南区": new BMap.Point(108.2833, 22.8087),
                                "武鸣区": new BMap.Point(108.2807, 23.1636),
                                "良庆区": new BMap.Point(108.3774, 22.7833),
                                "邕宁区": new BMap.Point(108.4659, 22.7507),
                                "隆安县": new BMap.Point(107.703, 23.1708),
                                "马山县": new BMap.Point(108.2034, 23.7233),
                                "上林县": new BMap.Point(108.5657, 23.4652),
                                "宾阳县": new BMap.Point(108.8093, 23.2219),
                                "横县": new BMap.Point(109.2054, 22.6848)
                            }, "柳州市": {
                                "": new BMap.Point(109.4153, 24.3136),
                                "城中区": new BMap.Point(109.4153, 24.3136),
                                "鱼峰区": new BMap.Point(109.4336, 24.3329),
                                "柳南区": new BMap.Point(109.4048, 24.3297),
                                "柳北区": new BMap.Point(109.4528, 24.3556)
                            }, "桂林市": {
                                "秀峰区": new BMap.Point(110.2875, 25.2797),
                                "叠彩区": new BMap.Point(110.2822, 25.3055),
                                "象山区": new BMap.Point(110.2857, 25.259),
                                "七星区": new BMap.Point(110.3078, 25.2711)
                            }
                        }
                    };

                    $(document).on("dblclick blur", "#c-address", function () {
                        var address = $(this).val();
                        if (address) {
                            geocoderSearch($("#city option:selected").text() + address);
                        }
                    });

                } else {
                }
            }, 500); // 延迟500ms初始化
        }
    }
});

$(document).ready(function () {
    // 获取select标签
    var allLocations = [];
    var selectElement = $('#c-classes_id');
    // 初始化allLocations数组


    // 生成表格的方法
    function generateTable() {
        allLocations = [];
        selectElement.find('option').each(function () {
            var location = {
                id: $(this).val(),
                name: $(this).text().trim(),
                level: parseInt($(this).attr('level')),
                parent: $(this).attr('parent')
            };
            allLocations.push(location);
        });

        // 获取选中的option的value
        var selectedLocations = selectElement.find('option:selected').map(function () {
            return $(this).val();
        }).get();

        // 过滤出选中的地点信息
        var filteredLocations = allLocations.filter(function (location) {
            return selectedLocations.includes(location.id);
        });

        // 生成表格
        var tableHtml = '<table class="table table-striped"><thead><tr><th>ID</th><th>三级地址</th><th>二级地址</th><th>一级地址</th><th>操作</th></tr></thead><tbody>';

        filteredLocations.forEach(function (location) {
            // 查找父级和父父级地址
            var parentLocation = allLocations.find(function (loc) {
                return loc.id === location.parent;
            });
            var grandparentLocation = parentLocation ? allLocations.find(function (loc) {
                return loc.id === parentLocation.parent;
            }) : null;
            // 生成表格行 - 添加安全检查
            var parentName = parentLocation ? parentLocation.name : '无';
            var grandparentName = grandparentLocation ? grandparentLocation.name : '无';

            // 生成表格行
            tableHtml += '<tr><td>' + location.id + '</td><td>' + location.name + '</td><td>' + parentName + '</td><td>' + grandparentName + '</td><td><a href="#" class="btn btn-primary btn-xs">设置</a></td></tr>';

        });

        tableHtml += '</tbody></table>';

        // 将表格插入到页面中
        $('#table-container').html(tableHtml);
    }

    // 在select的change事件中调用生成表格的方法
    selectElement.change(function () {
        generateTable();
    });

    // 页面加载时生成初始表格
    generateTable();

});


if ($("#c-daytime-all").length > 0) {
    let daysOfWeek;
    let timePeriods;
    let options;
    let selectedOptions;
    disableWeekRangeSelect = document.getElementById('c-disable_week_range');
    mustWeekRange = document.getElementById('c-must_week_range');
    daytimeall = document.getElementById('c-daytime-all');
    daysOfWeek = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    timePeriods = ['上午', '中午', '下午', '晚上'];
    options = daysOfWeek.flatMap(day => {
        return timePeriods.map(period => {
            if (row && row.disable_week_range) {
                select = row.disable_week_range.split(",");
                if (select.includes(day + period)) {
                    return `<option value="${day}${period}" selected>${day}${period}</option>`;
                } else {
                    return `<option value="${day}${period}">${day}${period}</option>`;
                }
            } else {
                return `<option value="${day}${period}">${day}${period}</option>`;
            }
        });
    });
    daytimeall.innerHTML = options.join('');
    // 获取所有选中的选项
    selectOptions = Array.from(document.getElementById('c-daytime-all').options);
    $(document).on("change change2", "#c-daytime-all", function () {
        selectedOptions = Array.from(document.getElementById('c-daytime-all').selectedOptions);
        if (disableWeekRangeSelect) {
            disableWeekRangeSelect.innerHTML = ''; // 清空所有选项
            disableWeekRangeSelect.appendChild(new Option("不选择", ""));
            selectedOptions.forEach(option => {
                clonedOption3 = option.cloneNode(true);
                disableWeekRangeSelect.appendChild(clonedOption3);
            });
            disableWeekRangeSelect.addEventListener('change', function () {
                if (this.value === "") {
                    for (let i = 0; i < this.options.length; i++) {
                        if (this.options[i].value !== "") {
                            this.options[i].selected = false;
                        } else {
                            this.options[i].selected = true;
                        }
                    }
                }
            });
        }
        if (mustWeekRange) {
            mustWeekRange.innerHTML = ''; // 清空所有选项
            mustWeekRange.appendChild(new Option("不选择", ""));
            selectedOptions.forEach(option => {
                clonedOption4 = option.cloneNode(true);
                mustWeekRange.appendChild(clonedOption4);
            });
            mustWeekRange.addEventListener('change', function () {
                if (this.value === "") {
                    // 如果选择了"不选择"，则取消其他选项的选中状态
                    for (let i = 0; i < this.options.length; i++) {
                        if (this.options[i].value !== "") {
                            this.options[i].selected = false;
                        }
                    }
                }
            });
        }

        selectOptions.forEach(option => {
            clonedOption = option.cloneNode(true);
            mustWeekRange.appendChild(clonedOption);
            clonedOption2 = option.cloneNode(true);
            disableWeekRangeSelect.appendChild(clonedOption2);
        });
    });


    if (row && $('#c-daytime-all').count > 0) {
        select = row.daytimeall.split(",");
        $('#c-daytime-all option').prop('selected', false);
        daytimeall = document.getElementById('c-daytime-all');

        for (let i = 0; i < daytimeall.options.length; i++) {
            if (select.includes(daytimeall.options[i].value)) {
                daytimeall.options[i].selected = true;
            }
        }

        select1 = row.disable_week_range.split(",");
        $('#c-disable_week_range option').prop('selected', false);
        for (let i = 0; i < disableWeekRangeSelect.options.length; i++) {
            if (select1.includes(disableWeekRangeSelect.options[i].value)) {
                disableWeekRangeSelect.options[i].selected = true;
            }
        }

        $('#c-must_week_range option').prop('selected', false);
        select2 = row.must_week_range.split(",");
        for (let i = 0; i < mustWeekRange.options.length; i++) {
            if (select2.includes(mustWeekRange.options[i].value)) {
                mustWeekRange.options[i].selected = true;
            }
        }
    }


    if ($('input[name="row[daytime][]"]')) {
        // 监听复选框的点击事件
        $('input[name="row[daytime][]"]').click(function () {
            selectedOptions = Array.from(document.getElementById('c-daytime-all').selectedOptions);
            selectedOptions_m = Array.from(document.getElementById('c-must_week_range').selectedOptions);
            selectedOptions_d = Array.from(document.getElementById('c-disable_week_range').selectedOptions);

            // 获取选中的时段
            var selectedTime = $(this).val();

            // 获取下拉列表
            var select = $('#c-daytime-all');

            // 清空下拉列表
            select.empty();
            // 根据选中的时段生成选项
            $('input[name="row[daytime][]"]:checked').each(function () {
                var time = $(this).val();
                if (time == 1) {
                    select.append('<option value="周一上午">周一上午</option>');
                    select.append('<option value="周二上午">周二上午</option>');
                    select.append('<option value="周三上午">周三上午</option>');
                    select.append('<option value="周四上午">周四上午</option>');
                    select.append('<option value="周五上午">周五上午</option>');
                    select.append('<option value="周六上午">周六上午</option>');
                    select.append('<option value="周日上午">周日上午</option>');
                } else if (time == 3) {
                    select.append('<option value="周一下午">周一下午</option>');
                    select.append('<option value="周二下午">周二下午</option>');
                    select.append('<option value="周三下午">周三下午</option>');
                    select.append('<option value="周四下午">周四下午</option>');
                    select.append('<option value="周五下午">周五下午</option>');
                    select.append('<option value="周六下午">周六下午</option>');
                    select.append('<option value="周日下午">周日下午</option>');
                } else if (time == 4) {
                    select.append('<option value="周一晚上">周一晚上</option>');
                    select.append('<option value="周二晚上">周二晚上</option>');
                    select.append('<option value="周三晚上">周三晚上</option>');
                    select.append('<option value="周四晚上">周四晚上</option>');
                    select.append('<option value="周五晚上">周五晚上</option>');
                    select.append('<option value="周六晚上">周六晚上</option>');
                    select.append('<option value="周日晚上">周日晚上</option>');
                } else if (time == 2) {
                    select.append('<option value="周一中午">周一中午</option>');
                    select.append('<option value="周二中午">周二中午</option>');
                    select.append('<option value="周三中午">周三中午</option>');
                    select.append('<option value="周四中午">周四中午</option>');
                    select.append('<option value="周五中午">周五中午</option>');
                    select.append('<option value="周六中午">周六中午</option>');
                    select.append('<option value="周日中午">周日中午</option>');
                }
            });

            selectOptions = Array.from(document.getElementById('c-daytime-all').options);
            $(mustWeekRange).html("");
            $(disableWeekRangeSelect).html("");
            selectOptions.forEach(option => {
                clonedOption = option.cloneNode(true);
                mustWeekRange.appendChild(clonedOption);
                clonedOption2 = option.cloneNode(true);
                disableWeekRangeSelect.appendChild(clonedOption2);
            });
            select = selectedOptions.map(option => option.value);
            daytimeall = document.getElementById('c-daytime-all');
            for (let i = 0; i < daytimeall.options.length; i++) {
                if (select.includes(daytimeall.options[i].value)) {
                    daytimeall.options[i].selected = true;
                } else {
                    daytimeall.options[i].selected = false;
                }
            }

            select1 = selectedOptions_d.map(option => option.value);
            for (let i = 0; i < disableWeekRangeSelect.options.length; i++) {
                if (select1.includes(disableWeekRangeSelect.options[i].value)) {
                    disableWeekRangeSelect.options[i].selected = true;
                } else {
                    disableWeekRangeSelect.options[i].selected = false;
                }
            }

            select2 = selectedOptions_m.map(option => option.value);
            for (let i = 0; i < mustWeekRange.options.length; i++) {
                if (select2.includes(mustWeekRange.options[i].value)) {
                    mustWeekRange.options[i].selected = true;
                }
            }

        });
    }
}

// 监听学科层级树形下拉
$(document).on("change2", "#c-subjectlv_tree", function (e) {
    let that = $(this);
    $.ajax({
        url: "/subjectlv/subjectlv/liststree", type: "GET", dataType: "json", success: function (data) {
            that.empty();
            that.append('<option value="">请选择父级</option>');
            var list = data.list || data.data || [];
            // 支持树形结构，带缩进
            $.each(list, function (index, item) {
                var prefix = '';
                that.append('<option value="' + item.id + '">' + prefix + item.name.replace(/<[^>]+>/g, "") + '</option>');
            });
            if (typeof row !== 'undefined' && row && row.pid) {
                that.val(row.pid);
            }
        }, error: function (xhr, status, error) {
        }
    });
});


$(document).on("click change load", "#maxks,#c-classes-per-week,input[name='row[daytime][]'],input[name='row[weekdays][]'],select[name='row[disable_week_range][]'],.add-class,.remove-class,#DisableWeekTime,#DisableWeekRange", function () {
    sds = $("input[name='daytime']").length;
    zs = $("input[name='row[weekdays][]']:checked").length;
    jysds = $("#DisableWeekTime option:selected").length; //禁用时点数
    function timescount(targetChar) {
        var count2 = 0;  //检查上午有多少个？
        $("input[name=daytime]").each(function () {
            var value = $(this).val(); // 获取当前 input 的值
            if (value.includes(targetChar)) { // 检查值是否包含目标字符
                count2++; // 如果包含，则计数器加1
            }
        });
        return count2;
    }

    function hasweek(targetChar) {
        var result = false;  //检查是否有周一？
        $("input[name='row[weekdays][]']:checked").each(function () {
            var value = $(this).closest("label").html(); // 获取当前 input 的值
            if (value.includes(targetChar)) { // 检查值是否包含目标字符
                result = true;
                return false;
            }
        });
        return result;
    }

    jyzds = 0;
    $("#DisableWeekRange option:selected").each(function () {
        ss = $(this).text();
        shangzxw = ss.match(/上|中|下|晚/g);
        week = ss.match(/一|二|三|四|五|六|日/g);
        if (hasweek(week[0]) && timescount(shangzxw[0]) > 0) {
            jyzds += timescount(shangzxw[0]);
        }
    });
    count = sds * zs - jysds - jyzds;
    $("#maxks").html(count);
    if ($("#c-classes-per-week").val() > count) {
        $("#c-classes-per-week").val(count);
    }
});
$(document).ready(function () {
    setTimeout(function () {
        $("#maxks").trigger("change");
    }, 2000);
});


function httpInfo(jqXHR, ajaxSettings) {
    // 获取请求方法
    const method = ajaxSettings.method || 'GET';

    // 获取请求 URL
    const url = ajaxSettings.url;

    // 获取请求头
    const headers = ajaxSettings.headers || {};

    // 获取请求数据
    const data = ajaxSettings.data || {};

    // 获取响应头
    const responseHeaders = jqXHR.getAllResponseHeaders();

    // 组合成完整的 HTTP 报头
    const httpRequestHeader = `
        Request Method: ${method}
        Request URL: ${url}
        Request Headers: ${JSON.stringify(headers, null, 2)}
        Request Data: ${JSON.stringify(data, null, 2)}
        Response Headers: ${responseHeaders}
    `;


}


$(document).on("mousedown", "#c-disable_week_range, #c-must_week_range, #c-daytime-all,.selects", function () {
    if (!event.ctrlKey) {
        event.preventDefault();
    }
});


//toggleGuide
$('#toggleGuide').click(function () {
    var content = $('#guideContent');
    var icon = $(this).find('i');
    if (content.is(':visible')) {
        content.slideUp();
        icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
        $(this).html('<i class="fa fa-chevron-down"></i> 展开');
    } else {
        content.slideDown();
        icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
        $(this).html('<i class="fa fa-chevron-up"></i> 收起');
    }
});


if ($('#c-school_id').length > 0) {
    $("#c-school_id").trigger("change2");
}
if ($('#c-community_id').length > 0) {
    $("#c-community_id").trigger("change2");
}

if ($('#c-addresslv_id_tree').length > 0) {
    $("#c-addresslv_id_tree").trigger("change2");
}

if ($('select[name="row[community_id]"]').length > 0) {
    $("select[name='row[community_id]']").trigger("change2");
}

if ($('select[name="row[subject_lv]"]').length > 0) {
    $("select[name='row[subject_lv]']").trigger("change2");
}

if ($('#c-subject_lv2').length > 0) {
    $("#c-subject_lv2").trigger("change2");
}

if ($('#c-subject_lv3,#c-subjecct-lv3-pid').length > 0) {
    $("#c-subject_lv3,#c-subjecct-lv3-pid").trigger("change3");
}

if ($('#c-ocation_id').length > 0) {
    $('#c-ocation_id').trigger("change2");
}
if ($('#c-ocation_id_community').length > 0) {
    $('#c-ocation_id_community').trigger("change2");
}
if ($('#c-coursetype_tree').length > 0) {
    $('#c-coursetype_tree').trigger("change2");
}


if ($('#c-table_id').length > 0) {
    $('#c-table_id').trigger("change2");
}

if ($('#c-ocation_pid').length > 0) {
    $('#c-ocation_pid').trigger("change2");
}

if ($('#c-receiver_id').length > 0) {
    $('#c-receiver_id').trigger("change2");
}

if ($('#c-cityarea_id').length > 0) {
    $('#c-cityarea_id').trigger("change2");
}

if ($('#c-ocation_class').length > 0) {
    $('#c-ocation_class').trigger("change2");
}

if ($('#c-address_lv_octionlevel').length > 0) {
    $('#c-address_lv_octionlevel').trigger("change2");
}

if ($('#c-classes_id').length > 0) {
    $('#c-classes_id').trigger("change2");
}


if ($('#c-student_id').length > 0) {
    $('#c-student_id').trigger("change2");
}


if ($('#c-user_id').length > 0) {
    $('#c-user_id').trigger("change2");
}

if ($('#c-user_id2').length > 0) {
    $('#c-user_id2').trigger("change2");
}

if ($('#c-teacher_id').length > 0) {
    $('#c-teacher_id').trigger("change2");
}

if ($('#c-message_type').length > 0) {
    $('#c-message_type').trigger("change2");
}

if ($('#c-column_id').length > 0) {
    // 使用多种方式确保事件被触发
    function triggerColumnChange() {
        $('#c-column_id').trigger("change2");
    }

    // 方法1：延迟触发
    setTimeout(triggerColumnChange, 500);

    // 方法2：确保DOM完全加载后触发
    $(window).on('load', triggerColumnChange);

    // 方法3：如果元素是动态添加的，使用事件委托
    $(document).on('DOMNodeInserted', function (e) {
        if ($(e.target).is('#c-column_id') || $(e.target).find('#c-column_id').length > 0) {
            triggerColumnChange();
        }
    });
}

if ($('#c-address_lv').length > 0) {
    $('#c-address_lv').trigger("change2");
}

if ($('#c-class_type').length > 0) {
    $('#c-class_type').trigger("change2");
}
if ($('#c-classes_type').length > 0) {
    $('#c-classes_type').trigger("change2");
}

if ($('#c-address_lv_pid').length > 0) {
    $('#c-address_lv_pid').trigger("change4");
}

if ($('#c-address_lv3,#c-addresslv_id3').length > 0) {
    $('#c-address_lv3,#c-addresslv_id3').trigger("change3");
}

//仅一二级地址可选
if ($('#c-address_lv4,#c-addresslv_id4').length > 0) {
    $('#c-address_lv4,#c-addresslv_id4').trigger("change4");
}

if ($('#c-rel_type').length > 0) {
    $('#c-rel_type').trigger("change3");
}

if ($('select[group]').length > 0) {
    if ($("#c-school_id").length > 0) {
        $("#c-school_id").closest("div.form-group").hide();
    }
    if ($("#c-community_id").length > 0) {
        $("#c-community_id").closest("div.form-group").hide();
    }
    $('select[group]').trigger("change3");
}

if ($('#group').length > 0) {
    if ($("#c-school_id").length > 0) {
        $("#c-school_id").closest("div.form-group").hide();
    }
    if ($("#c-community_id").length > 0) {
        $("#c-community_id").closest("div.form-group").hide();
    }
    $('#group').trigger("change2");
}

if ($('#c-week').length > 0) {
    $('#c-week').trigger("change2");
}

if ($('#c-subjectlv_tree').length > 0) {
    $('#c-subjectlv_tree').trigger('change2');
}

if ($("#c-subject_lv_level").length > 0) {
    $("#c-subject_lv_level").trigger("change2");
}

if ($('#c-communityCourse_id').length > 0) {
    $('#c-communityCourse_id').trigger('change2');
}
if ($('#c-ocation_id_sq').length > 0) {
    $('#c-ocation_id_sq').trigger('change2');
}


if ($('#c-course_id').length > 0) {
    $('#c-course_id').trigger("change2");
}
if ($('#c-publicwelfare_id').length > 0) {
    $('#c-publicwelfare_id').trigger("change2");
}
// 位置编号下拉框数据加载
$(document).on("change change2", "#c-number", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/Category/lists?type=number", type: "GET", dataType: "json", success: function (data) {
                var $number = that;
                $number.empty();
                $number.append('<option value="">请选择位置编号</option>');
                var list = data.list || data.data || [];
                $.each(list, function (index, item) {
                    $number.append('<option value="' + item.id + '"  data-image-width="' + item.image_width + '" data-image-height="' + item.image_height + '">' + item.name + '</option>');
                });
                if (row && row.number) {
                    that.val(row.number);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            }, error: function (xhr, status, error) {
            }
        });
    }
});

if ($('#c-number').length > 0) {
    $('#c-number').trigger("change2");
}